Python Script to Download YouTube Videos

YouTube is one of the most popular video-sharing platforms in the world, offering a vast array of content for users to enjoy. Whether it’s for entertainment, education, or simply for reference, watching YouTube videos can be a valuable part of our daily routine. However, what if you want to save a video for offline viewing or share it with others? This is where a YouTube video downloader comes in. In this tutorial, we’ll be exploring how to create a Python script to download videos from YouTube.

You can use this script to download YouTube videos in the highest resolution.

First you need to install the pytube package, in order to do that we can use pip:

pip install pytube

Once that is done you can copy the python script below to download your favorite YouTube videos:

from pytube import YouTube
import argparse
import os, sys

class YouTubeDownloader:

    def __init__(self, link): = link
        self.yt_obj = YouTube(, on_progress_callback=self._on_progress)
        self.done = False
        self._downloads = 0
        self._download_directory = "" 
        self._on_progress_enabled = False
    def download(self):
        video = self.yt_obj.streams.get_highest_resolution()
        video_filename = video.title.replace(" ", "_") + ".mp4", filename=video_filename)
        self.done = True
        self._downloads += 1
    def downloads() -> int:
        return self.downloads
    def set_download_path(self, path: str):
        os.makedirs(path, exist_ok=True)
        self._download_directory = path
    def enable_progress_bar(self):
        self._on_progress_enabled = True 
    def disable_prgress_bar(self):
        self._on_progress_enabled = False 
    def get_progress_bar_status(self): 
        return self._on_progress_enabled
    def __str__(self):
        info = f"Title: {self.yt_obj.title}\n"
        info = info + f"Author: {}\n"
        info = info + f"Views: {self.yt_obj.views}"
        return info

    def  _on_progress(self, stream, chunk, bytes_remaining):
        if not self._on_progress_enabled:
        # Calculate the percentage of the stream that has been downloaded
        percentage = (stream.filesize - bytes_remaining) / stream.filesize * 100
        bar = int(percentage/5)
        newline = "\n" if percentage == 100 else ""
        sys.stdout.write("\r[{0}{1}] {2:.2f}%{3}".format('#' * bar,' '*(20-bar), percentage,newline))
if __name__=="__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('-l', '--link', help='YouTube video link for download')
    args = parser.parse_args()
    yt_downloader = YouTubeDownloader(
    if yt_downloader.done:
        print("Download is done")


python -l


Title: The Beatles - A Day In The Life
Author: TheBeatlesVEVO
Views: 144750455
[####################] 100.00%
Download is done

check for the downloaded file under the directory “downloads

1 thought on “Python Script to Download YouTube Videos”

Leave a Comment