Python library PyTube to download youtube videos

YouTube is the world's most popular video sharing platform. Sometimes you want to download videos for offline viewing, but most YouTube downloader apps have restrictions or cost money. Instead, you can create your own Python program using the PyTube library to download YouTube videos easily.

PyTube is a lightweight, dependency-free Python library that allows you to download videos and audio from YouTube. Since it's not a standard library, you need to install it first ?

Installation

pip install pytube
Collecting pytube
  Downloading pytube-15.0.0-py3-none-any.whl
Installing collected packages: pytube
Successfully installed pytube-15.0.0

Basic Video Download

Let's start by importing the YouTube class and creating a simple downloader ?

from pytube import YouTube

# Create YouTube object with video URL
yt = YouTube('https://www.youtube.com/watch?v=dQw4w9WgXcQ')

# Display video information
print("Title:", yt.title)
print("Author:", yt.author)
print("Views:", yt.views)
print("Length:", yt.length, "seconds")
Title: Rick Astley - Never Gonna Give You Up (Official Video)
Author: Rick Astley
Views: 1400000000
Length: 213 seconds

Accessing Video Metadata

PyTube provides easy access to video information ?

from pytube import YouTube

yt = YouTube('https://www.youtube.com/watch?v=dQw4w9WgXcQ')

print("Thumbnail URL:", yt.thumbnail_url)
print("Description:", yt.description[:100] + "...")
print("Rating:", yt.rating)
print("Keywords:", yt.keywords[:3])  # First 3 keywords
Thumbnail URL: https://i.ytimg.com/vi/dQw4w9WgXcQ/sddefault.jpg
Description: The official video for "Never Gonna Give You Up" by Rick Astley...
Rating: None
Keywords: ['rick astley', 'never gonna give you up', 'official']

Selecting Video Quality and Format

You can view all available streams and choose the desired quality ?

from pytube import YouTube

yt = YouTube('https://www.youtube.com/watch?v=dQw4w9WgXcQ')

# Show all available streams
print("All streams:")
for stream in yt.streams:
    print(stream)

print("\nVideo-only streams:")
for stream in yt.streams.filter(only_video=True):
    print(stream)

print("\nAudio-only streams:")
for stream in yt.streams.filter(only_audio=True):
    print(stream)
All streams:
<Stream: itag="18" mime_type="video/mp4" res="360p" fps="30fps" vcodec="avc1.42001E" acodec="mp4a.40.2">
<Stream: itag="22" mime_type="video/mp4" res="720p" fps="30fps" vcodec="avc1.64001F" acodec="mp4a.40.2">
<Stream: itag="140" mime_type="audio/mp4" abr="128kbps" acodec="mp4a.40.2">

Video-only streams:
<Stream: itag="137" mime_type="video/mp4" res="1080p" fps="30fps" vcodec="avc1.640028">
<Stream: itag="136" mime_type="video/mp4" res="720p" fps="30fps" vcodec="avc1.4d401f">

Audio-only streams:
<Stream: itag="140" mime_type="audio/mp4" abr="128kbps" acodec="mp4a.40.2">
<Stream: itag="171" mime_type="audio/webm" abr="128kbps" acodec="vorbis">

Downloading Videos

Download the highest quality MP4 video available ?

from pytube import YouTube

yt = YouTube('https://www.youtube.com/watch?v=dQw4w9WgXcQ')

# Get highest quality MP4 stream
stream = yt.streams.get_highest_resolution()

# Download to current directory
stream.download()

# Or download to specific path
# stream.download('C:/Downloads/')

print("Download completed!")

Downloading Audio Only

Extract only the audio track from a video ?

from pytube import YouTube

yt = YouTube('https://www.youtube.com/watch?v=dQw4w9WgXcQ')

# Get audio stream
audio_stream = yt.streams.filter(only_audio=True).first()

# Download audio
audio_stream.download(filename='audio.mp4')

print("Audio downloaded successfully!")

Complete Example

Here's a complete script that downloads a video with user choice ?

from pytube import YouTube

def download_video(url, download_path='.'):
    try:
        # Create YouTube object
        yt = YouTube(url)
        
        print(f"Title: {yt.title}")
        print(f"Duration: {yt.length} seconds")
        
        # Get available qualities
        streams = yt.streams.filter(progressive=True, file_extension='mp4')
        
        print("\nAvailable qualities:")
        for i, stream in enumerate(streams):
            print(f"{i+1}. {stream.resolution} - {stream.filesize} bytes")
        
        # User selects quality
        choice = int(input("Enter choice (1-{}): ".format(len(streams))))
        selected_stream = streams[choice-1]
        
        # Download video
        print("Downloading...")
        selected_stream.download(download_path)
        print("Download completed!")
        
    except Exception as e:
        print(f"Error: {e}")

# Usage
url = input("Enter YouTube URL: ")
download_video(url)

Common Stream Filters

Filter Method Purpose Example
filter(only_video=True) Video without audio High-quality video files
filter(only_audio=True) Audio only Music downloads
filter(progressive=True) Video with audio Complete video files
filter(file_extension='mp4') Specific format MP4 files only

Conclusion

PyTube makes downloading YouTube videos simple with just a few lines of Python code. You can access video metadata, choose quality, and download both video and audio streams. Always respect copyright laws and YouTube's terms of service when downloading content.

Updated on: 2026-03-25T05:24:29+05:30

628 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements