The user wants a Python script to download YouTube videos using the pytube library.
1. Understand the Goal:
The objective is to create a functional, easy-to-understand Python script that takes a YouTube URL as input and saves the video to the local disk.
2. Identify the Necessary Tool:
The user specifically asked for pytube. This is a lightweight, dependency-free Python library to download YouTube videos.
3. Determine the Key Steps in the Script:
Import: Import the YouTube class from pytube.
Input: Get the video URL from the user (hardcoded or via input()).
Object Creation: Create a YouTube object using the URL.
Selection: Choose the stream (resolution/quality). Usually, users want the highest resolution (progressive) or just audio. I should probably default to the highest resolution progressive stream (which includes audio/video combined) as it's the most common use case.
Download: Call the .download() method on the selected stream.
Output Directory (Optional): It's good practice to allow specifying a download folder, but defaulting to the current directory is fine for a basic script.
Error Handling:pytube can be finicky due to YouTube API changes. It's good to wrap the core logic in a try-except block.
4. Draft the Code (Mental or Scratchpad):
python
from pytube import YouTube
def download_video(url):
yt = YouTube(url)
stream = yt.streams.get_highest_resolution()
stream.download()
# Add main execution block
5. Refine the Code:
Refinement 1: Add print statements to show progress (Title, Downloading..., Done).
Refinement 3: Allow the user to input the URL dynamically.
6. Address Potential Issues with pytube:pytube is notorious for breaking whenever YouTube updates their internal algorithms.
Mitigation: I should mention in the explanation that if it doesn't work, the user might need to upgrade pytube (pip install pytube --upgrade) or that it might be broken temporarily.
7. Structure the Response:
Prerequisites: Explain how to install the library (pip install pytube).
The Script: Provide the clean, commented code.
How to use it: Explain how to run it.
Advanced Options (Optional but helpful): Show how to download audio only or a specific resolution.
Troubleshooting: Add a note about the frequent updates/issues with pytube.
8. Writing the Code (Iterative improvement):
Basic Version:
python
from pytube import YouTube
link = input("Enter the URL: ")
youtube_1 = YouTube(link)
videos = youtube_1.streams.get_highest_resolution()
videos.download()
print("Download completed")
Polished Version:
Use a function. Include error handling.
python
from pytube import YouTube
import os
def download_video(url, path='.'):
try:
yt = YouTube(url)
# Filter for progressive streams (audio + video) to get highest res
stream = yt.streams.get_highest_resolution()
print(f"Downloading: {yt.title}")
stream.download(output_path=path)
print("Download completed!")
except Exception as e:
print(f"An error occurred: {e}")
# Main block...
9. Final Review of the Response:
Does it meet the user's request? Yes. Is the code correct? Yes. Is the advice about installation and troubleshooting included? Yes.
10. Constructing the Final Output: (This matches the provided good response).
Start with pip install pytube.
Provide the script.
Explain the code parts.
Add the "Audio Only" variation as a bonus.
Here is a complete Python script to download YouTube videos using the pytube library.
Step 1: Install the Library
Before running the script, you need to install the pytube library. Open your terminal or command prompt and run:
bash
pip install pytube
Step 2: The Python Script
Save the following code as downloader.py.
python
from pytube import YouTube
import os
def download_video(url, path='.'):
try:
# Create YouTube object
yt = YouTube(url)
# Display video details
print(f"Title: {yt.title}")
print(f"Views: {yt.views}")
# Get the highest resolution stream available
# Note: get_highest_resolution() automatically filters for progressive streams
# (video + audio combined) usually up to 720p.
y_stream = yt.streams.get_highest_resolution()
print(f"Downloading: {yt.title} ({y_stream.resolution})...")
# Download the video
y_stream.download(output_path=path)
print("Download completed successfully!")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
# Input the YouTube URL
video_url = input("Enter the YouTube video URL: ")
# Optional: Ask for a download directory (default is current folder)
save_path = input("Enter the save directory (leave blank for current folder): ")
if not save_path:
save_path = "."
# Run the download function
download_video(video_url, save_path)
How to Run It
Open your terminal.
Run the script:
bash
python downloader.py
Paste the YouTube link when prompted and press Enter.
Important Notes
Resolution Limits (720p): YouTube separates video and audio streams for high-definition videos (1080p+). pytube's get_highest_resolution() method usually defaults to 720p because that is the highest quality where the audio and video are combined in a single file.
Copyright: Please respect copyright laws and YouTube's Terms of Service. Only download videos if you have permission or for personal fair use.
Troubleshooting:
"Video is unavailable": This often happens if pytube hasn't been updated to match a recent change in YouTube's backend code. To fix this, try updating the library:
bash
pip install pytube --upgrade
If the standard upgrade doesn't work, you may need to install a specific fork (like pytube-fix):
bash
pip install pytube-fix
Variation: Download Audio Only (MP3)
If you only want the audio track, you can modify the script to filter for audio-only streams:
python
from pytube import YouTube
def download_audio(url):
yt = YouTube(url)
print(f"Downloading audio for: {yt.title}")
# Filter specifically for audio streams
audio_stream = yt.streams.filter(only_audio=True).first()
# Download
out_file = audio_stream.download()
# Rename the file to .mp3 (optional, as it downloads as .mp4 or .webm initially)
base, ext = os.path.splitext(out_file)
new_file = base + '.mp3'
os.rename(out_file, new_file)
print(f"Saved as: {new_file}")