#!/usr/bin/env python3
"""
YouTube Video Downloader using pytube.
A simple script to download YouTube videos in the highest available MP4 quality.
Requirements:
- Python 3.6+
- pytube: Install with `pip install pytube`
Usage:
python youtube_downloader.py <YouTube_URL>
OR
python youtube_downloader.py (will prompt for URL)
Example:
python youtube_downloader.py https://www.youtube.com/watch?v=dQw4w9WgXcQ
Notes:
- Downloads the highest resolution progressive MP4 stream (video + audio).
- Saves to the current directory by default (use --output to change).
- Handles basic errors like invalid URLs.
- Progress bar is shown during download.
"""
import argparse
import sys
from pathlib import Path
from pytube import YouTube
def download_video(url: str, output_path: Path) -> None:
"""
Download a YouTube video.
"""
try:
# Create YouTube object
yt = YouTube(url)
# Display video info
print(f"Title: {yt.title}")
print(f"Author: {yt.author}")
print(f"Duration: {yt.length // 60}:{yt.length % 60:02d} ({yt.length} seconds)")
print(f"Views: {yt.views:,}")
print("-" * 50)
# Get the highest resolution progressive MP4 stream (includes audio)
stream = (yt.streams
.filter(progressive=True, file_extension='mp4')
.order_by('resolution')
.desc()
.first())
if not stream:
print("No suitable progressive MP4 stream found. Trying highest resolution video-only...")
stream = yt.streams.get_highest_resolution()
if not stream:
raise Exception("No downloadable streams available.")
print(f"Downloading: {stream.resolution or 'Unknown'} - {stream.filesize / (1024*1024):.1f} MB")
print("-" * 50)
# Download with progress bar (built into pytube)
filepath = stream.download(output_path=output_path)
print(f"\n✅ Download completed! Saved to: {filepath}")
except Exception as e:
print(f"❌ Error: {str(e)}", file=sys.stderr)
sys.exit(1)
def main():
parser = argparse.ArgumentParser(description="Download YouTube videos with pytube.")
parser.add_argument("url", nargs="?", help="YouTube video URL")
parser.add_argument("-o", "--output", default=".", type=Path,
help="Output directory (default: current directory)")
args = parser.parse_args()
# Get URL from args or prompt
url = args.url
if not url:
url = input("Enter YouTube URL: ").strip()
if not url:
print("No URL provided.", file=sys.stderr)
sys.exit(1)
# Validate output path
output_path = args.output.resolve()
output_path.mkdir(parents=True, exist_ok=True)
download_video(url, output_path)
if __name__ == "__main__":
main()
Quick Start
Install pytube:
code
pip install pytube
(Note: If you encounter cipher issues with recent YouTube changes, update with pip install --upgrade pytube or check for forks like yt-dlp as alternatives.)