Introduction
YouTube is one of the leading video-sharing platforms in the world. Nowadays, everyone likes to watch videos online. But if you're a programmer and you like to perform a creative task using programming language, then you must know these cool python tricks that you're going to learn here.
In this tutorial, You will learn to make a YouTube downloader in Python using a few lines of code.
Python offeres a library called pytube. You might be surprised to hear that we can download videos from YouTube using this pytube library.
I've made a simple python project that can download videos and audios from YouTube in a very few steps.
The program will take three inputs from You.
👉URL of the video that You want to download,
👉The download path of Your computer, and
👉The resolution of the video from the options.
One more feature You can see in this project is the progress bar. It shows the amount of data downloaded from the web at the time of downloading.
⏰Visit Also: Create an Advanced Alarm Clock Using Python Tkinter
Installation Process
progress: pip install progress
Important Note |
---|
This Python Project works under the Command Line interface. You can make it a GUI-based application using python Tkinter. |
The Code
# YouTube Downloader in Python
from pytube import YouTube
from pytube.cli import on_progress
from progress.spinner import MoonSpinner
import time
# Progress bar(Optional)
spinner = MoonSpinner('Loading... ')
FINISHED = False
while not FINISHED:
for i in range(100):
time.sleep(0.01)
spinner.next()
FINISHED = True
spinner.finish()
# Inputs from the user
URL = input("Enter URL Here: ")
Download_Path = input("Enter Download path: ")
print("Select Quality:-")
quality_list = {
'1': '144p',
'2': '360p',
'3': '480p',
'4': '720p',
'5': 'Audio Only'
}
# Showing resolution options
for i, q in quality_list.items():
print(f"{i}.{q}")
chosen = input("\nEnter the number you've chosen: ")
# Creating YouTube videos.
yt = YouTube(URL, on_progress_callback=on_progress)
print(f"\nTitle: {yt.title}\n")
# Select option 5 to download only Audio from the YouTube
try:
if chosen != '5':
video = yt.streams.filter(mime_type="video/mp4", \
res=quality_list[chosen], progressive=True).first()
video.download(output_path=Download_Path)
elif chosen == '5':
audio = yt.streams.filter(type="audio").first()
audio.download(output_path=Download_Path)
print("\nDownload Completed!")
except Exception as es:
print(f"Error due to {es}")
Download The Code
Download the code from my GitHub account(subhankar-rakshit) through the download button.
Explanation of the above Code
from pytube import YouTube
from pytube.cli import on_progress
from progress.spinner import MoonSpinner
import time
All the imported modules have been used throughout the program.
👉on_progress: for tracking the amount of data downloaded from the web.
👉MoonSpinner: used here to add a progressing environment at the beginning of the program.
👉Pytube: A python library for downloading YouTube videos.
# Progress bar
spinner = MoonSpinner('Loading... ')
FINISHED = False
while not FINISHED:
for i in range(100):
time.sleep(0.01)
spinner.next()
FINISHED = True
spinner.finish()
As I discussed earlier, MoonSpinner has been used here to make the program more fascinating. I've used a for loop and time.sleep(0.01) to hold the program in sleep mode for a while.
This part is optional. Simply you can escape this code. It'll not harm the rest of the program.
print("Select Quality:-")
quality_list = {
'1': '144p',
'2': '360p',
'3': '480p',
'4': '720p',
'5': 'Audio Only'
}
# Showing options of Resolution
for i, q in quality_list.items():
print(f"{i}.{q}")
chosen = input("\nEnter the number you've chosen: ")
A Python Dictionary has been used here for containing multiple options for the resolution of the video.
Option #5 is only for audio. Users can download only the audio version of a video by choosing this option.
yt = YouTube(URL, on_progress_callback=on_progress)
print(f"\nTitle: {yt.title}\n")
The video URL(taken from the user) has been passed as a first argument into the YouTube class.
on_progress_callback=on_progress: for the progress bar.
yt.title returns the title of the video.
try:
if chosen != '5':
# video url.streams.first
video = yt.streams.filter(mime_type="video/mp4",
res=quality_list[chosen], progressive=True).first()
video.download(output_path=Download_Path)
elif chosen == '5':
audio = yt.streams.filter(type="audio").first()
audio.download(output_path=Download_Path)
print("\nDownload Completed!")
except Exception as es:
print(f"Error due to {es}")
Firstly I've used try and except methods for handling any exceptions. There are two options, if the user chooses option 5, then only the audio file will download; otherwise the program will download the video file.
yt.streams() returns a list containing a bunch of stream options. Users have to choose only one among them.
I've used the .filter() method to get only a specific option for download.
"res" refers to the resolution, progressive refers to the progressive stream, and mime_type refers to the type of the video(mp4 or webm).
You can add more filter options in the filter method. For instance, video codec, acodec, fps, etc.
download(): It downloads the video file in the folder provided there.
🍎Visit Also: Apple Catcher Game in Python - PyGame Projects
Conclusion
There are currently many websites that allow us to download youtube videos from YouTube. But since we are learning programming, We must try to do all those things by Our own programs.
In this tutorial, You've learned to download videos and audios from YouTube using python programming.
I hope You've enjoyed this tutorial. You can leave any of Your queries in the comment section below. You'll get a reply soon.
Thanks for reading!💙
It would help me a lot
ReplyDeleteThanks for sharing. I've built a YT downloader in TypeScript/Angular that connects to a backend server API that I created. My capabilities include single video downloads as either a video or a audio file, and the ability to download entire playlists as a zip file. Works really well!
ReplyDelete