Breaking News

Download Complete Playlist from Youtube using Python

Getting List of Urls:

We will use the following script to get all urls from a playlist and then store them in a list. The we will use youtube downloader from pytube to download videos one by one

import re
import urllib.request
import urllib.error
import sys
import time
from collections import OrderedDict

def crawl(url):
    sTUBE = ''
    cPL = ''
    amp = 0
    final_url = []

    if 'list=' in url:
        eq = url.rfind('=') + 1
        print(eq)
        cPL = url[eq:]

    else:
        print('Incorrect Playlist.')

    try:
        yTUBE = urllib.request.urlopen(url).read()
        sTUBE = str(yTUBE)
    except urllib.error.URLError as e:
        print(e.reason)

    tmp_mat = re.compile(r'watch\?v=\S+?list=' + cPL)
    mat = re.findall(tmp_mat, sTUBE)

    if mat:

        for PL in mat:
            yPL = str(PL)
            if '&' in yPL:
                yPL_amp = yPL.index('&')
            final_url.append('http://www.youtube.com/' + yPL[:yPL_amp])

        all_url = list(OrderedDict.fromkeys(final_url))

        i = 0
        while i < len(all_url):
            sys.stdout.write(all_url[i] + '\n')
            time.sleep(0.04)
            i = i + 1
        return final_url

    else:
        print('No videos found.')
        exit(1)


url = "https://www.youtube.com/watch?v=PJ4t2U15ACo&list=PLeo1K3hjS3uub3PRhdoCTY8BxMKSW7RjN"
if 'http' not in url:
    url = 'http://' + url
listUrl = crawl(url)

Downloading Videos from List of Urls:

Youtube videos can be easily downloaded using Python. We use a library named Pytube to download video.

from pytube import Youtube

Now we will define the save path and url to download video from youtube.

#where to save
SAVE_PATH = "H:/Youtube Downloads/" #to_do
 
#link of the video to be downloaded
link='https://www.youtube.com/watch?v=-9UjK-mWm7s'

Now we will download video using YouTube

#object creation using YouTube which was imported in the beginning
yt = YouTube(link)

#filters out all the files with "mp4" extension
yt = yt.streams.first()
try:
    #downloading the video
    yt.download(SAVE_PATH)
except:
    print("error")
# On complete print success Message
print("Task Completed")

So whole code will look like this

from pytube import Youtube
#where to save
SAVE_PATH = "H:/Youtube Downloads/" #to_do
 
def downloadVideo(link):
    #object creation using YouTube which was imported in the beginning
    yt = YouTube(link)

    #filters out all the files with "mp4" extension
    yt = yt.streams.first()
    try:
        #downloading the video
        yt.download(SAVE_PATH)
    except:
        print("error")

for url in listUrl:
    downloadVideo(url)

# On complete print success Message
print("Task Completed")

No comments