1 min read

YouTube Video Downloader

This utility downloads videos from YouTube using the pytube library. It fetches the highest resolution progressive stream (video and audio combined) available.

Modules Used:

  • pytube: A lightweight, dependency-free Python library (and command-line utility) for downloading YouTube Videos.
  • argparse: To handle command-line arguments.

Installation

pip install pytube

The Code

Save this as downloader.py.

from pytube import YouTube
import argparse
import sys
import os

def download_video(url, output_path):
    try:
        # Create YouTube object
        yt = YouTube(url)

        # Display metadata
        print(f"Title:  {yt.title}")
        print(f"Author: {yt.author}")
        print(f"Length: {yt.length} seconds")

        # Get the highest resolution progressive stream
        # Progressive streams contain both audio and video
        stream = yt.streams.get_highest_resolution()

        if not stream:
            print("Error: No suitable stream found.")
            return

        print(f"Downloading '{yt.title}' to {output_path}...")

        # Download
        stream.download(output_path)
        print("Download completed successfully!")

    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="YouTube Video Downloader")
    parser.add_argument("url", help="YouTube Video URL")
    parser.add_argument("-o", "--output", default=".", help="Output directory (default: current directory)")

    args = parser.parse_args()

    download_video(args.url, args.output)

Usage

python downloader.py "https://www.youtube.com/watch?v=dQw4w9WgXcQ"

programming/python/python