The user is asking for a Python script using the pytube library to download YouTube videos. They'd like it to be concise yet informative, including installation instructions and error handling. I'll propose a script that prompts for a URL, a download path, and potentially resolution options. It's important to mention the potential copyright issues and respect YouTube's Terms of Service. A disclaimer is necessary, emphasizing that the user should only download content they have rights to. I'll present both a minimal and advanced version of the script.Creating YouTube download script with pytube
I'm planning to use the pytube library for this script, reminding the user to install it via pip install pytube. I'm considering providing an example that downloads the highest resolution video while showing a progress bar using pytube.cli. Although there can be issues with age-restricted videos, I’ll focus on creating a simple script that takes a URL through command line input. I’ll also include error handling, setting an output path, and managing progress updates. Let's get started! Below is a simple, ready-to-run Python script that uses pytube to download YouTube videos.
Important: Only download videos if you own them, have permission from the copyright holder, or they are in the public domain / under a license that allows downloading. Also follow YouTube’s Terms of Service.
1. Install pytube
bash
pip install pytube
If you get errors, sometimes this helps:
bash
pip install --upgrade pytube
2. Minimal script: download the highest-resolution video
python
# file: download_youtube.py
from pytube import YouTube
def download_video(url: str, output_path: str = "."):
"""
Download the highest resolution progressive stream of a YouTube video.
:param url: URL of the YouTube video
:param output_path: Folder where the video will be saved (default: current directory)
"""
try:
yt = YouTube(url)
print(f"Title: {yt.title}")
print(f"Author: {yt.author}")
print("Downloading...")
# Get highest resolution stream that includes both video and audio
stream = yt.streams.get_highest_resolution()
# Download to the specified directory
file_path = stream.download(output_path=output_path)
print(f"Download completed: {file_path}")
except Exception as e:
print("An error occurred while downloading the video:")
print(e)
if __name__ == "__main__":
video_url = input("Enter YouTube video URL: ").strip()
output_folder = input("Enter output folder (leave blank for current folder): ").strip()
if not output_folder:
output_folder = "."
download_video(video_url, output_folder)
Run it:
bash
python download_youtube.py
3. Optional: choose resolution and show progress
Here’s a slightly more advanced version that:
Lists available resolutions
Lets you choose one
Shows a simple progress indicator
python
# file: download_youtube_advanced.py
from pytube import YouTube
def on_progress(stream, chunk, bytes_remaining):
total_size = stream.filesize
bytes_downloaded = total_size - bytes_remaining
completion = bytes_downloaded / total_size * 100
print(f"\rDownloading... {completion:.2f}%", end="")
def choose_stream(yt: YouTube):
# Filter progressive streams (video + audio) and sort by resolution
streams = yt.streams.filter(progressive=True, file_extension="mp4").order_by("resolution").desc()
if not streams:
print("No progressive mp4 streams available.")
return None
print("\nAvailable video options:")
for i, s in enumerate(streams, start=1):
print(f"{i}. {s.resolution} - {round(s.filesize / (1024 * 1024), 2)} MB")
while True:
choice = input("Choose a stream number (or press Enter for highest resolution): ").strip()
if not choice:
return streams.first()
try:
idx = int(choice)
if 1 <= idx <= len(streams):
return streams[idx - 1]
except ValueError:
pass
print("Invalid choice. Try again.")
def download_video(url: str, output_path: str = "."):
try:
yt = YouTube(url, on_progress_callback=on_progress)
print(f"\nTitle: {yt.title}")
print(f"Author: {yt.author}")
print(f"Length: {yt.length} seconds")
stream = choose_stream(yt)
if not stream:
return
print(f"\nSelected: {stream.resolution}, {round(stream.filesize / (1024 * 1024), 2)} MB")
print("Starting download...")
file_path = stream.download(output_path=output_path)
print(f"\nDownload completed: {file_path}")
except Exception as e:
print("\nAn error occurred while downloading the video:")
print(e)
if __name__ == "__main__":
video_url = input("Enter YouTube video URL: ").strip()
output_folder = input("Enter output folder (leave blank for current folder): ").strip()
if not output_folder:
output_folder = "."
download_video(video_url, output_folder)
If you tell me your exact use case (e.g., “download only audio as MP3”, “download entire playlist”, “integrate into a GUI”), I can adapt the script accordingly.