Building a YouTube Video Downloader in Python

Introduction
Downloading videos from YouTube is a popular automation task for offline viewing, content archiving, and educational use. Python offers an excellent library called pytube that makes this process simple and effective.
In this article, you’ll learn how to create a YouTube video downloader that:
Accepts a YouTube video URL
Lists available video streams (resolutions and formats)
Downloads the selected stream to your local machine
Let’s walk through it step by step.
Step 1: Install Required Library
We will use the pytube library. You can install it using pip:
pip install pytube
Note: If you're behind a firewall or experience issues, upgrade using:
pip install --upgrade pytube
Step 2: Import Necessary Modules
Start your Python script by importing the required module.
from pytube import YouTube
We only need YouTube from pytube, which allows us to work with video objects and streams.
Step 3: Get the YouTube Video URL
Prompt the user to enter a video URL.
video_url = input("Enter the YouTube video URL: ")
This URL will be passed to the YouTube class to initialize the video object.
Step 4: Initialize the YouTube Object
try:
yt = YouTube(video_url)
print(f"\nTitle: {yt.title}")
print(f"Author: {yt.author}")
print(f"Length: {yt.length} seconds")
except Exception as e:
print("Error loading video:", e)
exit()
This block:
Initializes the video
Displays some basic information
Handles errors gracefully (invalid links, network issues, etc.)
Step 5: List Available Streams
Now, we’ll list all available video streams with progressive download (video + audio combined).
streams = yt.streams.filter(progressive=True).order_by('resolution').desc()
print("\nAvailable Streams:")
for i, stream in enumerate(streams):
print(f"{i + 1}. {stream.resolution} - {stream.mime_type}")
.filter(progressive=True)ensures the streams include both video and audio..order_by('resolution')sorts them by quality.
Step 6: Choose and Download a Stream
Let the user choose a stream number and download the corresponding file.
try:
choice = int(input("\nEnter the number of the stream to download: "))
selected_stream = streams[choice - 1]
print("Downloading...")
selected_stream.download()
print("Download complete!")
except (IndexError, ValueError):
print("Invalid choice.")
The
.download()method saves the file in the current working directory.You can also pass a folder path to
download()if you want to change the location.
Full Script: YouTube Video Downloader in One Go
from pytube import YouTube
# Step 1: Get video URL from user
video_url = input("Enter the YouTube video URL: ")
# Step 2: Initialize the YouTube object
try:
yt = YouTube(video_url)
print(f"\nTitle: {yt.title}")
print(f"Author: {yt.author}")
print(f"Length: {yt.length} seconds")
except Exception as e:
print("Error loading video:", e)
exit()
# Step 3: List available progressive streams
streams = yt.streams.filter(progressive=True).order_by('resolution').desc()
print("\nAvailable Streams:")
for i, stream in enumerate(streams):
print(f"{i + 1}. {stream.resolution} - {stream.mime_type}")
# Step 4: Get user choice and download
try:
choice = int(input("\nEnter the number of the stream to download: "))
selected_stream = streams[choice - 1]
print("Downloading...")
selected_stream.download()
print("Download complete!")
except (IndexError, ValueError):
print("Invalid choice.")
Optional Enhancements
Download only audio
Add an option to filter audio streams:yt.streams.filter(only_audio=True)Choose download folder
selected_stream.download(output_path="C:/Users/You/Downloads")Show file size before downloading
print(f"File size: {round(selected_stream.filesize / 1024 / 1024, 2)} MB")
Conclusion
With just a few lines of Python, you’ve built a powerful YouTube downloader that lets users choose video quality and download content locally. It’s a great example of how to interact with web services and media files using Python.




