YouTube Video Downloader in Python.
About the project: This program will ask you for a YouTube video URL, let you choose the video quality, and then download the video to your computer.
For this project, we shall use Python's built-in tkinter library, which is a standard GUI toolkit.
This will allow us to create a window with a button and a display area for the dice roll, making it more interactive than a text-based application.
To use this YouTube Video Downloader, you'll first need to install the pytube library.
Open your terminal or command prompt and run:
pip install pytube
How to use this program:
- Run the Python script.
- The program will ask you to enter a YouTube video URL.
- It will then display the video's title, author, views, and a list of available resolutions for download.
- Enter the number corresponding to your desired resolution.
- You'll be prompted to enter a download path. If you leave it empty, the video will be saved in the same directory as your script.
- The video will then start downloading, and you'll see a confirmation message once it's complete.
- You can continue to download more videos or type q to quit at any prompt.
Once installed, you can run the Python script:
Project Level: Beginner
You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.
Steps: Follow these stepsStep 1: Copy below code using green 'copy' button.
Step 2: Paste the code on your chosen editor.
Step 3: Save the code with filename and .py extention.
Step 4: Run (Press F5 if using python IDLE)
# youtube_video_downloader.py
from pytube import YouTube
import os
def download_video():
"""
Prompts the user for a YouTube video URL, allows selection of quality,
and downloads the video.
"""
print("--- Python YouTube Video Downloader ---")
print("Enter 'q' at any time to quit.")
while True:
video_url = input("\nEnter the YouTube video URL: ").strip()
if video_url.lower() == 'q':
print("Exiting YouTube Video Downloader. Goodbye!")
break
if not video_url:
print("URL cannot be empty. Please enter a valid URL.")
continue
try:
yt = YouTube(video_url)
print(f"\nTitle: {yt.title}")
print(f"Author: {yt.author}")
print(f"Views: {yt.views:,}")
# Filter for progressive streams (downloadable video + audio)
# and sort by resolution
available_streams = yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc()
if not available_streams:
print("No downloadable MP4 streams found for this video.")
continue
print("\nAvailable Resolutions:")
for i, stream in enumerate(available_streams):
print(f"{i+1}. {stream.resolution} ({stream.filesize / (1024*1024):.2f} MB)")
while True:
try:
choice = input("Enter the number of the resolution you want to download: ").strip()
if choice.lower() == 'q':
print("Download cancelled.")
break # Break out of resolution choice loop
selected_index = int(choice) - 1
if 0 <= selected_index < len(available_streams):
selected_stream = available_streams[selected_index]
break # Valid choice, break out of resolution choice loop
else:
print("Invalid choice. Please enter a valid number.")
except ValueError:
print("Invalid input. Please enter a number.")
if choice.lower() == 'q': # If user quit from resolution choice
continue # Go back to main loop for new URL
# Get download path
download_path = input("Enter download path (leave empty for current directory): ").strip()
if not download_path:
download_path = "." # Current directory
if not os.path.isdir(download_path):
try:
os.makedirs(download_path)
print(f"Created directory: {download_path}")
except OSError as e:
print(f"Error creating directory '{download_path}': {e}")
continue # Go back to main loop for new URL
print(f"\nDownloading '{yt.title}' in {selected_stream.resolution}...")
selected_stream.download(output_path=download_path)
print("Download complete!")
print(f"Video saved to: {os.path.abspath(os.path.join(download_path, selected_stream.default_filename))}")
except Exception as e:
print(f"An error occurred: {e}")
print("Please check the URL or your internet connection.")
# Ask if the user wants to download another video
another_download = input("\nDo you want to download another video? (yes/no): ").strip().lower()
if another_download != 'yes':
print("Exiting YouTube Video Downloader. Goodbye!")
break
# This ensures that download_video() is called only when the script is executed directly.
if __name__ == "__main__":
download_video()