Python | Full Youtube Playlist Downloader

Python Methods and Functions

Required modules —

 BeautifulSoup bs4 PyQt5 sys module urllib module pytube module 

How does it work?
At the specified YouTube playlist URL, our program will clean up the web pages, retrieve all YouTube video links, and add them to the link array. Then, using the pytube library we will download the relevant YouTube videos from the link in the links array. Parameters for downloading YouTube videos (quality, mime_type, etc.) can be specified in the stream constructor. Videos will be uploaded with the name of the original video.

Let's see the code:

# Importing libraries

import bs4 as bs

import sys

import urllib.request

from PyQt5.QtWebEngineWidgets import QWebEnginePage

from PyQt5.QtWidgets import QApplication

from PyQt5.QtCore import QUrl

import pytube # library for downloading YouTube videos

 

 

class Page (QWebEnginePage):

def __ init __ ( self , url):

self . app = QApplication (sys.argv)

QWebEnginePage .__ init __ ( self )

self . html = ' '

  self .loadFinished.connect ( self ._ on_load_finished)

self . load (QUrl (url))

self . app.exec_ ()

 

def _on_load_finished ( self ):

  self . html = self . toHtml ( self . Callable )

print ( 'Load finished' )

 

def Callable ( self , html_str):

self . html = html_str

  self . app.quit ()

 

 

links = []

  

  

def exact_link (link):

vid_id = link.split ( '=' )

# print (vid_id)

str = ""

for i in vid_id [ 0 : 2 ]:

str + = i + "="

 

str_new = str [ 0 : len ( str ) - 1 ]

index = str_new.find ( "& amp;" )

 

new_link = " https://www.youtube.com " + str_new [ 0 : index]

return new_link

 

 

url = " https://www.youtube.com/watch?v=lcJzw0JGfeE&list=PLqM7alHXFySENpNgw27MzGxLzNJuC_Kdj "

# Scraping and extracting video
# links from the given playlist URL

page = Page (url)

count = 0

 

soup = bs.BeautifulSoup (page.html, ' html.parser' )

for link in soup.find_all ( 'a' , id = 'thumbnail' ):

 

# doesn't use the first link because it's

# is a playlist link, not a link on video

  if count = = 0

  count + = 1

continue

else :

vid_src = link [ 'href' ]

  # print (vid_src)

# keeping the link format to be

  # passed to pytube otherwise

new_link = exact_link (vid_src) 

 

# this may cause an error

# print (new_link)

 

  # add link to array of links

links.append (new_link) 

 
# print (links)

 
# download each video from
# link in an array of links

for link in links: 

  yt = pytube.YouTube (link)

 

  # The uploaded video will be of the best quality

stream = yt .streams. filter (progressive = True ,

file_extension = 'mp4' ). order_by (

'resolution' ). desc () .first () 

try :

stream.download ()

# print uploaded links

print ( "Downloaded:" , link) 

except :

print ( 'Some error in downloading:' , link)

Output:





Get Solution for free from DataCamp guru