YouTube Video Downloader Python Project with Source Code | Step-by-Step Guide

Faraz

By Faraz -

Create a YouTube video downloader using Python with this comprehensive project guide. Access the full source code and learn to download YouTube videos effortlessly.


youtube-video-downloader-python-project-with-source-code-step-by-step-guide.webp

Table of Contents

  1. Basic YouTube Video Downloading Script
  2. YouTube Video Downloader Graphical User Interface (GUI)
  3. Extracting Audio Only (YouTube Audio Downloader)
  4. Packaging the Youtube Video Downloader Application

Have you ever wanted to download your favorite YouTube videos for offline viewing? Perhaps you're preparing a presentation, or maybe you just want to save data on your mobile plan. Whatever your reason, creating a YouTube downloader in Python is a fun and practical project. In this article, we'll guide you through building your own downloader step by step.

Setting Up the Environment

Before we dive into the code, let's set up our environment.

Installing Python

First things first, you'll need Python installed on your computer. Head over to the official Python website and download the latest version. Follow the installation instructions specific to your operating system.

Required Libraries

We'll primarily use the Pytube library, which makes downloading YouTube videos a breeze. To install Pytube, open your terminal or command prompt and type:

pip install pytube

Understanding YouTube's Download Mechanism

Before we jump into coding, it's important to understand how YouTube serves videos and the legal considerations involved.

How YouTube Serves Videos

YouTube streams videos using a combination of video and audio streams. These are usually delivered via adaptive bitrate streaming, which means the quality of the video can change dynamically based on your internet speed.

Legal Considerations

Downloading YouTube videos is against YouTube's terms of service unless you have permission from the content creator. Always ensure you're respecting copyright laws and YouTube's policies.

Installing Pytube Library

What is Pytube?

Pytube is a lightweight, dependency-free Python library that allows for easy downloading of YouTube videos. It handles most of the complexities for you, making the process straightforward.

How to Install Pytube

As mentioned earlier, installing Pytube is as simple as running:

pip install pytube

Basic YouTube Video Downloading Script

Now, let's write our first script to download a YouTube video.

Writing the Script

Open your favorite text editor and create a new Python file, youtube_downloader.py. Here's a basic script to get you started:

from pytube import YouTube

# Prompt user for the YouTube video URL
video_url = input("Enter the YouTube video URL: ")

# Create a YouTube object
yt = YouTube(video_url)

# Get the highest resolution stream available
stream = yt.streams.get_highest_resolution()

# Download the video
stream.download()

print("Download completed!")

Running the Script

To run the script, open your terminal, navigate to the directory where your script is saved, and type:

python youtube_downloader.py

Enter a YouTube video URL when prompted, and watch as your video downloads!

Enhancing the Script

Let's add some user-friendly features to our script.

Adding User Input

We can prompt the user for more options, such as choosing the resolution.

from pytube import YouTube

video_url = input("Enter the YouTube video URL: ")
yt = YouTube(video_url)

# Display available streams
streams = yt.streams.filter(progressive=True)
for i, stream in enumerate(streams):
    print(f"{i}. {stream}")

# Prompt user to select a stream
stream_number = int(input("Enter the number of the stream you want to download: "))
selected_stream = streams[stream_number]

# Download the selected stream
selected_stream.download()

print("Download completed!")

Downloading Different Video Resolutions

Now, the user can choose from available video resolutions, enhancing the flexibility of your downloader.

Handling Errors and Exceptions

Errors are inevitable, so let's make our script more robust.

Common Errors

  • Invalid URL
  • Network issues
  • Video not available

How to Handle Them

We can use try-except blocks to handle these errors gracefully.

from pytube import YouTube
from pytube.exceptions import VideoUnavailable

video_url = input("Enter the YouTube video URL: ")

try:
    yt = YouTube(video_url)
except VideoUnavailable:
    print("The video is unavailable.")
    exit()

streams = yt.streams.filter(progressive=True)
for i, stream in enumerate(streams):
    print(f"{i}. {stream}")

stream_number = int(input("Enter the number of the stream you want to download: "))
selected_stream = streams[stream_number]

selected_stream.download()

print("Download completed!")

Downloading Playlists

Want to download an entire playlist? Let's modify our script to handle this.

Script Modifications for Playlists

from pytube import Playlist

playlist_url = input("Enter the YouTube playlist URL: ")
playlist = Playlist(playlist_url)

print(f"Downloading: {playlist.title}")

for video in playlist.videos:
    video.streams.get_highest_resolution().download()
    print(f"Downloaded: {video.title}")

print("All videos downloaded!")

Running the Playlist Script

Run this script the same way you did with the single video script. This time, it will download all videos in the playlist.

YouTube Video Downloader Graphical User Interface (GUI)

For a more user-friendly experience, let's build a simple GUI using Tkinter.

Introduction to Tkinter

Tkinter is Python's standard GUI library. It's simple to use and works across different platforms.

Building a Simple GUI for the Downloader

Here's a basic example to get you started:

import tkinter as tk
from pytube import YouTube

def download_video():
    url = url_entry.get()
    yt = YouTube(url)
    stream = yt.streams.get_highest_resolution()
    stream.download()
    result_label.config(text="Download completed!")

# Setting up the GUI window
window = tk.Tk()
window.title("YouTube Downloader")

tk.Label(window, text="Enter YouTube URL:").pack()
url_entry = tk.Entry(window, width=50)
url_entry.pack()

download_button = tk.Button(window, text="Download", command=download_video)
download_button.pack()

result_label = tk.Label(window, text="")
result_label.pack()

window.mainloop()

Advanced Features

Let's add some advanced features to make our downloader even more powerful.

Adding Download Progress Bar

You can show download progress by updating the GUI during the download.

import tkinter as tk
from pytube import YouTube
from threading import Thread

def download_video():
    url = url_entry.get()
    yt = YouTube(url, on_progress_callback=on_progress)
    stream = yt.streams.get_highest_resolution()
    stream.download()
    result_label.config(text="Download completed!")

def on_progress(stream, chunk, bytes_remaining):
    total_size = stream.filesize
    bytes_downloaded = total_size - bytes_remaining
    percentage = bytes_downloaded / total_size * 100
    progress_label.config(text=f"{percentage:.2f}% downloaded")

# Setting up the GUI window
window = tk.Tk()
window.title("YouTube Downloader")

tk.Label(window, text="Enter YouTube URL:").pack()
url_entry = tk.Entry(window, width=50)
url_entry.pack()

download_button = tk.Button(window, text="Download", command=lambda: Thread(target=download_video).start())
download_button.pack()

progress_label = tk.Label(window, text="")
progress_label.pack()

result_label = tk.Label(window, text="")
result_label.pack()

window.mainloop()

Extracting Audio Only (YouTube Audio Downloader)

Sometimes, you might just want the audio. Here's how to do that:

from pytube import YouTube

video_url = input("Enter the YouTube video URL: ")
yt = YouTube(video_url)

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

print("Audio download completed!")

Packaging the Youtube Video Downloader Application

To share your Youtube video downloader with others, you can package it into an executable file.

Creating an Executable File

Use tools like PyInstaller to create an executable:

pip install pyinstaller
pyinstaller --onefile youtube_downloader.py

Sharing Your Downloader

Share the executable file with your friends or upload it to a platform like GitHub.

Conclusion

In this article, we've walked through the process of creating a YouTube downloader in Python. From setting up your environment and writing a basic script to adding advanced features and building a GUI, we've covered it all. With this knowledge, you can now build and customize your own YouTube downloader.

That’s a wrap!

I hope you enjoyed this article

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺