Last modified: Feb 05, 2026 By Alexander Williams
Download YouTube Videos with Python: A Guide
Python makes many tasks easy. Downloading YouTube videos is one of them. This guide will show you how. We will use a popular library called Pytube. It is simple and powerful.
You will learn to install the library. You will write code to download videos. We will also cover handling errors. By the end, you can build your own downloader.
Why Use Python for YouTube Downloads?
Python is a versatile language. It has libraries for almost everything. Pytube is a lightweight library. It does not require complex setup.
Using Python gives you control. You can automate downloads. You can choose video quality. You can extract audio only. It is a valuable skill for any programmer.
Remember to respect copyright. Only download videos you have permission for. This guide is for educational use.
Setting Up Your Environment
First, you need Python installed. You can download it from python.org. Make sure it is added to your system path.
Next, install the Pytube library. Open your command line or terminal. Use the pip package manager. Run the following command.
pip install pytube
This command downloads and installs Pytube. Wait for the process to finish. You are now ready to write code.
Create a new Python file. Name it something like youtube_downloader.py. You will write all code in this file.
Basic Video Download with Pytube
Let's start with a simple script. This code downloads a video from a URL. You need the video's link. Copy it from your browser.
We import the YouTube class from Pytube. We create an object with the video URL. Then we get the highest resolution stream. Finally, we download it.
# Import the YouTube class from the pytube library
from pytube import YouTube
# The URL of the YouTube video you want to download
video_url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
# Create a YouTube object
yt = YouTube(video_url)
# Get the highest resolution progressive stream
video_stream = yt.streams.get_highest_resolution()
# Download the video to the current directory
print(f"Downloading: {yt.title}...")
video_stream.download()
print("Download complete!")
Run this script. The video will download to your current folder. The script prints the video title. It confirms when the download is done.
This is the core function. The download() method handles the file saving. It's that simple.
Choosing Video Quality and Format
You may not want the highest resolution. Pytube lets you choose. You can list all available streams. Then pick the one you need.
Use the streams property. It contains all formats. Filter by resolution or file type. The following code shows how.
from pytube import YouTube
video_url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
yt = YouTube(video_url)
# Print all available streams
print("Available streams:")
for stream in yt.streams:
print(stream)
# Filter for MP4 streams with 720p resolution
stream_720p = yt.streams.filter(file_extension='mp4', res="720p").first()
if stream_720p:
print(f"\nDownloading 720p MP4...")
stream_720p.download(output_path="./downloads")
else:
print("720p MP4 stream not found.")
The filter() method is powerful. You can specify resolution, file extension, and more. The first() method gets the first matching stream.
We also used an output_path parameter. This downloads the file to a specific folder. Here, it's a folder named "downloads".
Downloading Audio Only
Sometimes you only need the audio. Pytube can extract it. You filter streams for audio-only files. These are usually in MP4 or WebM format.
The following code finds the best audio stream. It downloads it as an MP4 file.
from pytube import YouTube
video_url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
yt = YouTube(video_url)
# Get the highest quality audio-only stream
audio_stream = yt.streams.get_audio_only()
print(f"Downloading audio: {yt.title}")
audio_stream.download(filename_prefix="audio_")
print("Audio download finished.")
The get_audio_only() method simplifies this. It returns the best audio stream. We add a filename prefix to identify it.
This is great for creating podcasts or music files. Always ensure you have the right to use the audio.
Handling Errors and Exceptions
Networks can fail. Videos can be private. Your code should handle errors. Use try-except blocks in Python.
Common exceptions include VideoUnavailable and RegexMatchError. Catching them makes your program robust.
from pytube import YouTube
from pytube.exceptions import VideoUnavailable, RegexMatchError
video_url = "https://www.youtube.com/watch?v=invalid"
try:
yt = YouTube(video_url)
stream = yt.streams.first()
stream.download()
print("Download successful.")
except VideoUnavailable:
print("Error: The video is unavailable or private.")
except RegexMatchError:
print("Error: The URL is not a valid YouTube link.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
This code tries to download a video. If the URL is bad, it catches the error. It prints a helpful message instead of crashing.
Always implement error handling. It is crucial for real-world applications.
Advanced: Downloading Playlists
Pytube can also handle playlists. You use the Playlist class. It gets all video URLs in a playlist. Then you download each one.
This is useful for courses or series. The process is similar to single videos.
from pytube import Playlist
# URL of a YouTube playlist
playlist_url = "https://www.youtube.com/playlist?list=PL_ABC123"
playlist = Playlist(playlist_url)
print(f"Downloading playlist: {playlist.title}")
for video_url in playlist.video_urls:
print(f"Processing: {video_url}")
yt = YouTube(video_url)
stream = yt.streams.get_highest_resolution()
stream.download(output_path="./playlist_downloads")
print("Playlist download complete.")
The code loops through each video URL. It downloads them one by one. All files save to a dedicated folder.
This can take a long time for large playlists. Consider adding delays between downloads.
Conclusion and Final Thoughts
You now know how to download YouTube videos with Python. We covered installation, basic downloads, and advanced options. The Pytube library is a powerful tool.
Remember to use this knowledge responsibly. Download only content you are allowed to. Respect creators' copyrights and terms of service.
Python can automate many media tasks. This skill can be part of larger projects. For instance, you could build a media archiver. You might combine it with other libraries for editing.
If you enjoy Python's versatility in media, you might find our Monty Python Video Games Guide an interesting read on a different type of Python content. Keep exploring and building.
Start with the basic script. Experiment with different streams. Add error handling. Soon you will have a reliable download tool.