How to Download Any YouTube Video Using Python

Downloading YouTube videos is a task that can be easily automated with Python. Whether you want to save a tutorial for offline viewing, download a favorite music video, or archive content, Python provides simple ways to achieve this using libraries like pytube.

In this blog, we will walk through the steps to create a Python program to download any YouTube video.


Introduction to pytube

pytube is a lightweight Python library that makes it easy to interact with YouTube videos. It allows users to download videos, extract metadata, and handle other YouTube functionalities.

Key Features of pytube:

  • Download videos from YouTube in various resolutions and formats.
  • Access video metadata such as title, description, and views.
  • Retrieve captions or subtitles (if available).

Step-by-Step Guide to Downloading YouTube Videos

Step 1: Install the pytube Library

Before we can start downloading YouTube videos, we need to install the pytube library. You can install it using pip, Python’s package manager. Open your terminal or command prompt and run:

pip install pytube

This will install the latest version of pytube.

Step 2: Write the Python Program

Now that we have installed pytube, let’s create the Python program to download a YouTube video.

# Import the YouTube class from the pytube module
from pytube import YouTube

# Input: Ask the user to enter the YouTube video URL
video_url = input("Enter the YouTube video URL: ")

# Create a YouTube object with the provided video URL
yt = YouTube(video_url)

# Display the video title
print(f"Downloading: {yt.title}")

# Get the highest resolution stream available for the video
video_stream = yt.streams.get_highest_resolution()

# Download the video to the current working directory
video_stream.download()

# Output: Inform the user that the download has completed
print(f"Download completed! The video has been saved as {yt.title}.")

Explanation of the Code:

  1. Importing the Library:
  • We import the YouTube class from the pytube library, which allows us to interact with a YouTube video.
  1. Input:
  • We prompt the user to input the URL of the YouTube video they want to download.
  1. Create YouTube Object:
  • The YouTube object is initialized with the video URL, allowing us to access the video’s details such as its streams (available formats and resolutions).
  1. Select Stream:
  • We use yt.streams.get_highest_resolution() to fetch the highest-quality video stream available.
  1. Download the Video:
  • We download the video by calling download() on the stream object. By default, the video will be saved in the current working directory.
  1. Output:
  • After the download is complete, a message is printed to notify the user.

Enhancing the Program: Let the User Choose Resolution

In the previous program, we downloaded the highest resolution available. However, some users may prefer to download videos in lower resolutions to save bandwidth or storage space. Let’s modify the program to allow the user to select the desired resolution.

from pytube import YouTube

# Input: Ask the user to enter the YouTube video URL
video_url = input("Enter the YouTube video URL: ")

# Create a YouTube object with the provided video URL
yt = YouTube(video_url)

# Display the video title
print(f"Downloading: {yt.title}")

# Display available stream resolutions
streams = yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution')
for i, stream in enumerate(streams, start=1):
    print(f"{i}. {stream.resolution}")

# Ask the user to choose a resolution
choice = int(input("Select the resolution number: ")) - 1

# Download the selected resolution
selected_stream = streams[choice]
selected_stream.download()

print(f"Download completed! The video has been saved as {yt.title}.")

Enhancements:

  1. Filter Streams: We use streams.filter(progressive=True, file_extension='mp4') to list only streams that include both video and audio, and are in MP4 format.
  2. User Selection: We loop through the available streams and allow the user to select which resolution to download.
  3. Download the Chosen Stream: Based on the user’s choice, the program downloads the selected video resolution.

Handling Errors and Invalid URLs

When working with user input, especially URLs, it’s always good practice to handle potential errors gracefully. For instance, the user may enter an invalid YouTube URL or encounter an issue with the network. Let’s update the program to handle such errors.

from pytube import YouTube
from pytube.exceptions import RegexMatchError

try:
    # Input: Ask the user to enter the YouTube video URL
    video_url = input("Enter the YouTube video URL: ")

    # Create a YouTube object with the provided video URL
    yt = YouTube(video_url)

    # Display the video title
    print(f"Downloading: {yt.title}")

    # Get the highest resolution stream available for the video
    video_stream = yt.streams.get_highest_resolution()

    # Download the video
    video_stream.download()

    print("Download completed!")
except RegexMatchError:
    print("Invalid YouTube URL. Please check and try again.")
except Exception as e:
    print(f"An error occurred: {e}")

Error Handling:

  1. RegexMatchError: This specific exception is raised if the provided URL doesn’t match YouTube’s format.
  2. General Exception Handling: The Exception block catches any other unexpected errors (e.g., network issues or permission errors) and prints an error message.

Saving to a Specific Directory

By default, the video is saved in the current working directory, but you can specify a different directory by passing the path to the download() method.

# Specify the directory where you want to save the video
output_path = "C:/Downloads/YouTubeVideos"

# Download the video to the specified directory
video_stream.download(output_path=output_path)

Conclusion

Downloading YouTube videos with Python is simple and can be achieved using the pytube library. Whether you’re downloading videos for offline viewing or automating your workflow, this program provides an easy-to-use solution. We started with a basic version that downloads the highest resolution video, and enhanced it to allow user-selected resolutions and better error handling.

Feel free to experiment with additional features, such as downloading only the audio stream, or adding a graphical user interface (GUI) using libraries like Tkinter.

Happy coding, and enjoy downloading YouTube videos effortlessly with Python!


Disclaimer:

Please ensure you comply with YouTube’s terms of service and copyright laws when downloading videos.

Share with our team

Leave a Comment