Pytube YouTube Downloader
Pytube is a Python 3 library designed for downloading YouTube videos and playlists. It handles various resolutions, formats, and audio-only extractions. Currently at version 15.0.0, it maintains an active release cadence, primarily updating to adapt to frequent changes in YouTube's frontend, which it scrapes to function.
Warnings
- breaking Pytube relies on scraping YouTube's frontend, making it highly susceptible to breaking changes when YouTube updates its site. This often manifests as `KeyError`, `RegexMatchError`, `HTTPError` (404, 403), or `AgeRestrictedError`.
- breaking Since version 11.0.0, downloading age-restricted videos explicitly requires user authentication. Attempts to download without authentication will raise an `AgeRestrictedError`.
- gotcha Pytube does not support downloading live streams. As of version 10.8.3, attempts to process a livestream URL will raise an exception (e.g., `LiveStreamError`).
- gotcha YouTube occasionally implements download throttling mechanisms by obfuscating URL parameters (e.g., the 'n' cipher). While `pytube` actively releases updates to bypass this (e.g., v10.9.0), issues can recur.
Install
-
pip install pytube
Imports
- YouTube
from pytube import YouTube
- Playlist
from pytube import Playlist
- Search
from pytube import Search
Quickstart
from pytube import YouTube
# Example: Download the highest resolution of a video
video_url = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ' # Rick Astley - Never Gonna Give You Up
try:
yt = YouTube(video_url)
print(f"Downloading: {yt.title}...")
# Get the highest resolution stream
stream = yt.streams.get_highest_resolution()
# Or, filter by resolution and file extension
# stream = yt.streams.filter(res="720p", file_extension='mp4').first()
if stream:
stream.download(output_path='./downloads')
print(f"Successfully downloaded '{yt.title}' to ./downloads")
else:
print("No suitable stream found.")
except Exception as e:
print(f"An error occurred: {e}")