How to Build a Python Program to Download YouTube Videos

YouTube is an incredibly popular video sharing platform with billions of monthly active users. It hosts a massive variety of content across every conceivable category. While it‘s great to be able to easily stream videos on demand, sometimes you may want to download a video to be able to view it offline, archive it in case it gets taken down, or use clips from it in your own projects.

The problem is, YouTube doesn‘t make it easy to download videos directly from the site. This is understandable since YouTube wants to keep users engaged on their platform in order to serve ads. They provide some limited offline viewing options, but you can‘t simply save a video file locally to your computer.

Fortunately, Python provides a way to automate downloading YouTube videos using third-party libraries. In this post, we‘ll walk through how to build a Python program that can download any YouTube video with just the video URL.

Setting Up Your Python Environment

Before we dive into the code, you‘ll need to make sure you have Python set up on your computer. This program will require Python 3.x.

First, check if you already have Python installed by opening a terminal and running:

python --version

If you see a Python version reported, then you‘re good to go. If not, you‘ll need to install Python from python.org. I recommend installing the latest version of Python 3.

Next, you‘ll need to install the pytube library which is what will allow us to interact with YouTube. pytube is a lightweight, dependency-free library specifically built for downloading YouTube videos.

You can install pytube using pip, Python‘s built-in package manager. In your terminal, simply run:

pip install pytube

With Python and pytube ready to go, open up your favorite code editor and let‘s start building our YouTube video downloader!

Downloading a YouTube Video

In a new Python file, let‘s start by importing the pytube library:

from pytube import YouTube

This imports the YouTube class which provides all the functionality we need to download videos.

Next, we‘ll define a function that will handle downloading the video given a YouTube video URL:

def download_video(url):
    yt = YouTube(url)

    print(f"Video Title: {yt.title}")
    print(f"Video Length: {yt.length / 60:.2f} minutes")

    stream = yt.streams.get_highest_resolution()
    print(f"Video Resolution: {stream.resolution}")

    print("Downloading video...")
    stream.download()
    print("Video downloaded successfully!")

Let‘s break this down step-by-step:

  1. We define a function called download_video that takes the url of the YouTube video we want to download.

  2. We create a YouTube object yt by passing in the url. This will make a request to fetch all the available information and metadata about the video.

  3. We print out the title and length of the video. pytube provides easy access to this metadata. We convert the length from seconds to minutes for readability.

  4. The streams attribute of the YouTube object contains all the different quality and format options available for the video. We use get_highest_resolution() to select the stream with the best video quality. You could modify this to select a different stream based on your requirements.

  5. We print out the chosen video resolution which will be something like "720p" or "1080p".

  6. Finally, we call the download() method on the selected stream to actually download the video file. By default this will save the video in the same directory as your Python script with the video title as the filename.

  7. We print a success message once the download is finished.

To actually use this function to download a video, we need to pass it a YouTube video URL. For example:

download_video("https://www.youtube.com/watch?v=dQw4w9WgXcQ")

When you run the full script, you should see output like:

Video Title: Rick Astley - Never Gonna Give You Up (Official Music Video)
Video Length: 3.56 minutes  
Video Resolution: 720p
Downloading video...
Video downloaded successfully!

And the music video for "Never Gonna Give You Up" by Rick Astley will be downloaded to your computer! Congratulations, you just built a working YouTube video downloader in only about 10 lines of Python code.

Customizing Your Downloader

Now that you have a basic version working, let‘s explore a few ways you can extend and customize it.

First, let‘s add an option to specify the output path where we want to save the downloaded video. pytube allows you to pass a filename parameter to the download() method:

    output_path = "/path/to/downloads/folder"
    stream.download(output_path=output_path)

Replace /path/to/downloads/folder with the actual folder path where you want to save your videos. For example C:\Users\username\Videos.

What if we want to be able to choose the specific resolution instead of always getting the highest available? pytube provides different methods to filter the available streams. Here‘s how you could select the 480p stream:

    stream = yt.streams.filter(progressive=True, file_extension=‘mp4‘, resolution="480p").first()

This filters the streams to only the progressive (audio + video) mp4 streams and selects the first one that matches 480p resolution. You can play around with the different stream filtering options in the pytube documentation.

Finally, let‘s add a bit of error handling in case something goes wrong:

def download_video(url):
    try:
        yt = YouTube(url)
    except:
        print(f"Failed to get video info for {url}")
        return

    # Video download code...

    try:    
        stream.download()
    except:
        print("Video download failed")
    else:
        print("Video downloaded successfully!")

We wrap the network requests to get the video info and download the video in try/except blocks. If getting the video info fails (e.g. invalid URL, no network connection), we print an error message and return early. If the actual video download fails (e.g. network error, disk space full) we print an error message, otherwise we print the success message.

Limitations and Gotchas

While this pytube-based YouTube downloader works great in many cases, there are a few limitations and potential issues to be aware of:

  • Some videos may have restrictions that prevent them from being downloaded, resulting in errors. This is more common for copyrighted content.
  • Live streams and non-video content like stories are not supported. Only standard YouTube videos can be downloaded.
  • There are a number of edge cases around stream availability and naming that pytube doesn‘t handle. You may occasionally get unexpected results or errors.
  • YouTube may change or break pytube by updating their site. The library maintainers usually fix issues quickly but there may be small windows where the library doesn‘t work.
  • Downloading videos may be against YouTube‘s terms of service. Be sure to only download videos you have the right to save locally.

Next Steps

With a working YouTube video downloader script, you can already save a lot of time and effort. But there are many ways you could enhance it further:

  • Build a simple user interface so you can paste in URLs and select options without editing the code
  • Set up a cron job or scheduled task to automatically check for and download new videos from your favorite channels
  • Extend the script to support playlists and channels in addition to individual videos
  • Integrate the downloader into a larger project like a media server or archival tool

The possibilities are endless! Python‘s extensive selection of packages makes it the perfect language for automating tasks like this.

Conclusion

YouTube may not make it easy to download videos, but with a little Python and the pytube library, you can automate the process with your own custom downloader script!

In this post, we covered how to set up your Python environment, use pytube to fetch video info and download streams, and customize the basic script to fit your needs. We also discussed some of the limitations and ways you could further extend your downloader.

Not only does this save you the time and hassle of manually downloading videos, it also gives you control over your data. You can archive your favorite content, edit and remix videos locally, or simply watch them without needing an internet connection.

This is just one example of how Python can be used to automate everyday tasks. With a little creativity and exploration of the Python package ecosystem, you can build your own specialized tools perfectly suited for your needs and workflows.

So go forth and download some videos! And let me know what other neat automation scripts you come up with.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *