Python Program to Download Youtube Videos

Python is popular programming language that has lot of libraries available to perform various tasks. One such task is downloading videos from YouTube. In this article we will discuss how to write a Python program to download YouTube videos using the pytube library.

Create Music Player in Python with Output

Any Language Translator in Python

Step by step Video Python Program to Download Youtube Videos

Python Program to Download Youtube Videos

Installing the Required Libraries

Before we start we need to install the required libraries. We will be using following libraries:

!pip install Progressbar
from tkinter import *
from tkinter import messagebox
from pytube import YouTube
from tqdm import tqdm
  • tkinter is Python GUI library.
  • messagebox is module in tkinter that provides a set of standard dialog boxes.
  • pytube is Python library for downloading YouTube videos.
  • tqdm is library for displaying progress bars in the command line

Complete Code:

from tkinter import *
from tkinter import messagebox
from pytube import YouTube
from tqdm import tqdm

def get_video():
    global streams
    # get the video link from the entry widget
    video_link = entry.get()
    try:
        # create a YouTube object
        yt = YouTube(video_link)
        # get the available video streams
        streams = yt.streams.filter(file_extension="mp4").order_by('resolution').desc()
        # populate the listbox with the available resolutions
        listbox.delete(0, END)
        for i, stream in enumerate(streams):
            listbox.insert(END, "{}. {}p".format(i+1, stream.resolution))
    except:
        messagebox.showerror("Error", "Invalid video link.")

def download_video():
    # get the selected video stream from the listbox
    resolution_choice = listbox.curselection()[0]
    global video
    video = streams[resolution_choice]

    # create a progress bar
    global progress
    progress = Progressbar(window, orient=HORIZONTAL, length=300, mode='determinate')
    progress.pack()

    # create a label to display the time remaining
    global time_label
    time_label = Label(window, text="")
    time_label.pack()

    # download the video and update the progress bar
    video_path = video.download(filename=video.title, output_path=".")
    progress['value'] = 100
    time_label.config(text="Download complete.")
    messagebox.showinfo("Download Complete", "The video has been downloaded successfully.")

def update_progress(stream, chunk, bytes_remaining):
    size = stream.filesize
    downloaded = size - bytes_remaining
    progress_value = int(downloaded / size * 100)
    progress['value'] = progress_value
    time_remaining = int(bytes_remaining / stream.file.speed)
    time_label.config(text="Time remaining: {} seconds".format(time_remaining))

# create the main window
window = Tk()
window.title("YouTube Downloader")

# create an entry widget for the video link
link_label = Label(window, text="Video Link:")
link_label.pack()
entry = Entry(window, width=50)
entry.pack()

# create a button to get the available video streams
button = Button(window, text="Get Video", command=get_video)
button.pack()

# create a listbox to display the available video streams
listbox_label = Label(window, text="Available Resolutions:")
listbox_label.pack()
listbox = Listbox(window)
listbox.pack()

# create a button to download the selected video stream
download_button = Button(window, text="Download", command=download_video)
download_button.pack()

# start the main loop
window.mainloop()
  • The function get_video is called when tuser clicks the “Get Video” button.
  • global streams is used to make streams variable available to other functions.
  • The function gets YouTube video link entered by the user in the entry widget.
  • A YouTube object is created with video link.
  • The filter() method is used to get available video streams with the file extension of “mp4”. The order_by() method is used to sort the streams by resolution in descending order.
  • The function populates listbox with available resolutions by deleting the previous items in the listbox and inserting new items with the insert() method. The enumerate() function is used to add a numbering system to the resolutions.
  • The function download_video is called when user clicks the “Download” button.
  • The curselection() method is used to get index of the selected resolution in the listbox.
  • global video is used to make video variable available to other functions.
  • The function creates a progress bar and a label to display the time remaining.
  • The download() method is used to download the video and progress bar is updated as the video is downloading.
  • Once the download is complete progress bar is set to 100 and the time label is updated to show that the download is complete. Finally, a message box is displayed to inform the user that the download is complete.
  • Inside the get_video() function a try-except block is used to catch any exceptions that may occur while creating a YouTube object from the video link entered by the user. If the video link is invalid, an error message is displayed using the messagebox.showerror() method.
  • If the video link is valid then available video streams are obtained by filtering the streams based on their file extension and ordering them based on their resolution. The obtained streams are stored in the streams global variable.
  • The listbox widget is then cleared using the listbox.delete() method and the available resolutions are displayed in the listbox widget using listbox.insert() method. The format of the resolution displayed is “{stream_number}. {resolution}p”, where the stream_number is the index of the stream in the streams list plus one, and the resolution is the resolution of the stream.
  • The download_video() function is called when user clicks the “Download” button. The function first gets the index of the selected stream from the listbox widget using the listbox.curselection() method. The selected stream is then stored in the video global variable.
  • A Progressbar widget is created to display progress of the video download. The Progressbar widget is oriented horizontally and has a length of 300 pixels. The progress bar is then packed into the main window using the pack() method.
  • A Label widget is created to display time remaining for the download to complete. The Label widget is then packed into the main window using the pack() method.
  • The video download is initiated by calling the download() method of selected stream object. The video is saved with a filename equal to the title of the video and saved in the current directory. As the video download progresses, the update_progress() function is called to update the progress bar and the time remaining label. When the download is complete, a message is displayed using the messagebox.showinfo() method.
  • The update_progress() function is defined to update progress bar and time remaining label during the video download. The function takes in the stream, chunk, and bytes_remaining parameters. The size of the file being downloaded is obtained from the stream.filesize attribute. The amount of data downloaded so far is calculated by subtracting the bytes_remaining from the size. The progress bar value is calculated as a percentage of the downloaded data over the total size of the file. The time remaining is calculated by dividing the bytes_remaining by the speed of the download.
  • Finally main window is created using Tk() constructor and various widgets such as labels entry, listbox, buttons progress bar, and label are added to it using the Label(), Entry(), Listbox(), Button(), Progressbar(), and Label() constructors, respectively. The pack() method is used to add the widgets to the window. mainloop() method is called to run the main event loop of the window.
Python Program to Download Youtube Videos

Here are some useful links related to downloading YouTube videos with Python:

  1. The official documentation of the pytube library: https://python-pytube.readthedocs.io/en/latest/
  2. The GitHub repository for pytube, where you can find source code and examples: https://github.com/pytube/pytube
  3. The documentation for the Python Standard Library’s tkinter module, which is used in the example code: https://docs.python.org/3/library/tkinter.html
  4. The documentation for the tqdm library, which provides a progress bar for downloads: https://tqdm.github.io/
  5. A tutorial on using pytube to download YouTube videos: https://www.geeksforgeeks.org/python-program-to-download-complete-youtube-playlist-without-using-any-third-party-library/

By Alan Turing

Welcome to our programming exercises for programmers challenge website! Here, you can hone your coding skills through a series of carefully curated exercises that cater to programmers of all levels. Our platform offers a variety of coding challenges, ranging from easy to hard, that allow you to practice various programming concepts and algorithms.Our exercises are designed to help you think critically and develop problem-solving skills. You can choose from a wide range of programming languages, including Python, Java, JavaScript, C++, and many more. With our intuitive and user-friendly interface, you can track your progress and monitor your performance, allowing you to identify areas for improvement.We also offer a community forum, where you can interact with other programmers, exchange ideas, and get feedback on your code. Our website is optimized for SEO, so you can easily find us through popular search engines. Join us today and take your programming skills to the next level!

Leave a Reply