Best code
from pytube import YouTube
import os
def download_youtube_video():
try:
# Get YouTube URL from user
url = input("Enter the YouTube video URL: ").strip()
# Create YouTube object
yt = YouTube(url)
# Select the highest resolution progressive stream (video + audio)
stream = yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first()
# If no progressive stream found, use the highest resolution (may require audio merge)
if not stream:
stream = yt.streams.get_highest_resolution()
# Display video details
print(f"\nDownloading: {yt.title}")
print(f"Resolution: {stream.resolution}\n")
# Download the video
output_path = "./downloads" # Customize download path
os.makedirs(output_path, exist_ok=True) # Create directory if it doesn't exist
stream.download(output_path)
print("\nDownload completed successfully!")
except Exception as e:
print(f"\nAn error occurred: {str(e)}")
if __name__ == "__main__":
download_youtube_video()
0 Comments