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):
        self.link = link
        self.yt_obj = YouTube(self.link, 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"
        video.download(output_path=self._download_directory, filename=video_filename)
        self.done = True
        self._downloads += 1
   
    @property 
    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: {self.yt_obj.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:
            return
        # 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))
        sys.stdout.flush()
          
        
if __name__=="__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('-l', '--link', help='YouTube video link for download')
    args = parser.parse_args()
    yt_downloader = YouTubeDownloader(args.link)
    yt_downloader.set_download_path("downloads")
    yt_downloader.enable_progress_bar()
    print(yt_downloader)
    yt_downloader.download()
    if yt_downloader.done:
        print("Download is done")

example:

python YouTubeDownloader.py -l https://www.youtube.com/watch?v=usNsCeOV4GM

output:

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