Download Youtube Video(s) or whole Playlist with Python - GeeksforGeeks

10 May, 2022
Prerequisite:
Tkinter
pyyoutube
pytube
threading in Tkinter
YouTube API
Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications.
In this article, we will discuss how we can create a GUI application to download a YouTube video or a complete YouTube playlist using python. 
Before we get started first we will discuss pyyoutube module. The pyyoutube module provides an easy way to use the YouTube Data API V3.
Installation:
pip install python-youtubepip install pytube
In this section, we will learn, how to download only selected videos from YouTube Playlist Using Tkinter in Python.
Approach:
First, we will fetch all video link from the YouTube playlist using the pyyoutube module.
Then we will select the video link, which we want to download.
Then we will download each video one by one using pytube module.
Below is what the GUI looks like:
Let’s Understand step by step implementation:
Create a Tkinter window and add Buttons, Labels, Scrollbar, etc...
Python3
# Import Required Modulesfrom tkinter import *  # Create Objectroot = Tk()  # Set geometryroot.geometry('400x400')  # Add LabelLabel(root, text="Youtube Playlist Downloader",      font="italic 15 bold").pack(pady=10)Label(root, text="Enter Playlist URL:-", font="italic 10").pack()  # Add Entry boxplaylistId = Entry(root, width=60)playlistId.pack(pady=5)  # Add Buttonget_videos = Button(root, text="Get Videos")get_videos.pack(pady=10)  # Add Scorllbarscrollbar = Scrollbar(root)scrollbar.pack(side=RIGHT, fill=BOTH)list_box = Listbox(root, selectmode="multiple")list_box.pack(expand=YES, fill="both")list_box.config(yscrollcommand=scrollbar.set)scrollbar.config(command=list_box.yview)  download_start = Button(root, text="Download Start", state=DISABLED)download_start.pack(pady=10)  # Execute Tkinterroot.mainloop()
Now we will create three functions:
get_list_videos:- It will give a list of all video links of a YouTube playlist.threading:- It is used for threading in Tkinter.download_videos:- It is used for downloading YouTube video.
get_list_videos:- It will give a list of all video links of a YouTube playlist.
threading:- It is used for threading in Tkinter.
download_videos:- It is used for downloading YouTube video.
Python3
def get_list_videos():    global playlist_item_by_id    # Clear ListBox    list_box.delete(0, 'end')      # Create API Object    api = Api(api_key='Enter API Key')      if "youtube" in playlistId.get():        playlist_id = playlistId.get()[len(            "https://www.youtube.com/playlist?list="):]    else:        playlist_id = playlistId.get()      # Get list of video links    playlist_item_by_id = api.get_playlist_items(        playlist_id=playlist_id, count=None, return_json=True)      # Iterate through all video links and insert into listbox    for index, videoid in enumerate(playlist_item_by_id['items']):        list_box.insert(            END, f" {str(index+1)}. {videoid['contentDetails']['videoId']}")      download_start.config(state=NORMAL)    def threading():    # Call download_videos function    t1 = Thread(target=download_videos)    t1.start()    def download_videos():    download_start.config(state="disabled")    get_videos.config(state="disabled")      # Iterate through all selected videos    for i in list_box.curselection():        videoid = playlist_item_by_id['items'][i]['contentDetails']['videoId']          link = f"https://www.youtube.com/watch?v={videoid}"          yt_obj = YouTube(link)          filters = yt_obj.streams.filter(progressive=True, file_extension='mp4')          # download the highest quality video        filters.get_highest_resolution().download()      messagebox.showinfo("Success", "Video Successfully downloaded")    download_start.config(state="normal")    get_videos.config(state="normal")
Below is the complete Implementation:
Python3
# Import Required Modulesfrom tkinter import *from pyyoutube import Apifrom pytube import YouTubefrom threading import Threadfrom tkinter import messagebox    def get_list_videos():    global playlist_item_by_id    # Clear ListBox    list_box.delete(0, 'end')      # Create API Object    api = Api(api_key='Enter API Key')      if "youtube" in playlistId.get():        playlist_id = playlistId.get()[len(            "https://www.youtube.com/playlist?list="):]    else:        playlist_id = playlistId.get()      # Get list of video links    playlist_item_by_id = api.get_playlist_items(        playlist_id=playlist_id, count=None, return_json=True)      # Iterate through all video links and insert into listbox    for index, videoid in enumerate(playlist_item_by_id['items']):        list_box.insert(            END, f" {str(index+1)}. {videoid['contentDetails']['videoId']}")      download_start.config(state=NORMAL)    def threading():    # Call download_videos function    t1 = Thread(target=download_videos)    t1.start()    def download_videos():    download_start.config(state="disabled")    get_videos.config(state="disabled")      # Iterate through all selected videos    for i in list_box.curselection():        videoid = playlist_item_by_id['items'][i]['contentDetails']['videoId']          link = f"https://www.youtube.com/watch?v={videoid}"          yt_obj = YouTube(link)          filters = yt_obj.streams.filter(progressive=True, file_extension='mp4')          # download the highest quality video        filters.get_highest_resolution().download()      messagebox.showinfo("Success", "Video Successfully downloaded")    download_start.config(state="normal")    get_videos.config(state="normal")    # Create Objectroot = Tk()# Set geometryroot.geometry('400x400')  # Add LabelLabel(root, text="Youtube Playlist Downloader",      font="italic 15 bold").pack(pady=10)Label(root, text="Enter Playlist URL:-", font="italic 10").pack()  # Add Entry boxplaylistId = Entry(root, width=60)playlistId.pack(pady=5)  # Add Buttonget_videos = Button(root, text="Get Videos", command=get_list_videos)get_videos.pack(pady=10)  # Add Scrollbarscrollbar = Scrollbar(root)scrollbar.pack(side=RIGHT, fill=BOTH)list_box = Listbox(root, selectmode="multiple")list_box.pack(expand=YES, fill="both")list_box.config(yscrollcommand=scrollbar.set)scrollbar.config(command=list_box.yview)  download_start = Button(root, text="Download Start",                        command=threading, state=DISABLED)download_start.pack(pady=10)  # Execute Tkinterroot.mainloop()
Output:
Here, we will learn, how to download the complete YouTube Playlist in Tkinter using Python.
Approach:
First, we will fetch all video links from the YouTube playlist using the pyyoutube module.
Then we will Iterate through all videos and download each video one by one using pytube module.
Below is what the GUI looks like:
Let’s Understand step by step implementation:
Create a Tkinter window and add Buttons, Labels, etc...
Python3
# Import Required Modulesfrom tkinter import *  # Create Objectroot = Tk()  # Set geometryroot.geometry('400x200')  # Add LabelLabel(root, text="Youtube Playlist Downloader",      font="italic 15 bold").pack(pady=10)Label(root, text="Enter Playlist URL:-", font="italic 10").pack()  # Add Entry boxplaylistId = Entry(root, width=60)playlistId.pack(pady=5)  download_start = Button(root, text="Download Start")download_start.pack(pady=10)  # Execute Tkinterroot.mainloop()
Now we will create two functions:
threading:- It is used for threading in Tkinter.download_videos:- It is used for downloading YouTube video.
threading:- It is used for threading in Tkinter.
download_videos:- It is used for downloading YouTube video.
Python3
def threading():    # Call download_videos function    t1 = Thread(target=download_videos)    t1.start()    def download_videos():    # Create API Object    api = Api(api_key='Enter API Key')      if "youtube" in playlistId.get():        playlist_id = playlistId.get()[len(            "https://www.youtube.com/playlist?list="):]    else:        playlist_id = playlistId.get()      # Get list of video links    playlist_item_by_id = api.get_playlist_items(        playlist_id=playlist_id, count=None, return_json=True)      # Iterate through all video links    for index, videoid in enumerate(playlist_item_by_id['items']):          link = f"https://www.youtube.com/watch?v={videoid['contentDetails']['videoId']}"          yt_obj = YouTube(link)          filters = yt_obj.streams.filter(progressive=True, file_extension='mp4')          # download the highest quality video        filters.get_highest_resolution().download()          print(f"Downloaded:- {link}")      messagebox.showinfo("Success", "Video Successfully downloaded")
Below is the complete Implementation:
Python3
# Import Required Modulesfrom tkinter import *from pyyoutube import Apifrom pytube import YouTubefrom threading import Threadfrom tkinter import messagebox    def threading():    # Call download_videos function    t1 = Thread(target=download_videos)    t1.start()    def download_videos():    # Create API Object    api = Api(api_key='Enter API Key')      if "youtube" in playlistId.get():        playlist_id = playlistId.get()[len(            "https://www.youtube.com/playlist?list="):]    else:        playlist_id = playlistId.get()      # Get list of video links    playlist_item_by_id = api.get_playlist_items(        playlist_id=playlist_id, count=None, return_json=True)      # Iterate through all video links    for index, videoid in enumerate(playlist_item_by_id['items']):          link = f"https://www.youtube.com/watch?v={videoid['contentDetails']['videoId']}"          yt_obj = YouTube(link)          filters = yt_obj.streams.filter(progressive=True, file_extension='mp4')          # download the highest quality video        filters.get_highest_resolution().download()          print(f"Downloaded:- {link}")      messagebox.showinfo("Success", "Video Successfully downloaded")    # Create Objectroot = Tk()# Set geometryroot.geometry('400x200')  # Add LabelLabel(root, text="Youtube Playlist Downloader",      font="italic 15 bold").pack(pady=10)Label(root, text="Enter Playlist URL:-", font="italic 10").pack()  # Add Entry boxplaylistId = Entry(root, width=60)playlistId.pack(pady=5)  download_start = Button(root, text="Download Start", command=threading)download_start.pack(pady=10)  # Execute Tkinterroot.mainloop()
Output:
anikaseth98
Python Tkinter-projects
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Create a directory in Python
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Python | Get unique values from a list