This article will discuss how to easily download music and videos from Youtube using the Python programming language. The reason why we will be using Python is that it is a lightweight, fast and easy tool to use for software development.
We will be using two libraries so as to achieve our aim argparse
and pytube
, it can be installed using the python package installer (pip
).
Importing the libraries
import argparse
from pytube import YouTube
To parse the arguments supplied to the script, we'll use argparse
, and to download YouTube videos, we'll use pytube
.
Next, we must provide the folders in which the video and audio should be stored. I do this by using the following constants:
VIDEO_DOWNLOAD_DIR = "../Downloads/videos"
AUDIO_DOWNLOAD_DIR = "..Downloads/audio"
Download function
Let's write a function that takes care of downloading the videos and audio in their respective folders separately.
For audio, we will filter the streams for audio-only content, choose the first one that is available, and download the audio-only stream to the AUDIO_DOWNLOAD_DIR
directory.
def YoutubeAudioDownload(video_url):
video = YouTube(video_url)
audio = video.streams.filter(only_audio = True).first()
try:
audio.download(AUDIO_DOWNLOAD_DIR)
except:
print("Failed to download audio")
print("audio was downloaded successfully")
For the video, the function takes the URL of the YouTube video and downloads the best/highest resolution available to the VIDEO_DOWNLOAD_DIR
directory.
def YoutubeVideoDownload(video_url):
video = YouTube(video_url)
video = video.streams.get_highest_resolution()
try:
video.download(VIDEO_DOWNLOAD_DIR)
except:
print("Unable to download video at this time!")
print("Video downloaded!")
These two simple functions take the YouTube video and audio URL, download it in the greatest resolution possible, and then save it in their respective directory, but if there is an error, it prints out an error message.
Main function
The video URL is parsed using argparse in the main function, and an optional audio-only flag is also used. The video's audio will be downloaded if the flag is enabled; by default, both the video and audio are downloaded.
These two simple functions take the YouTube video and audio URL, download it in the greatest resolution possible, and then save it in their respective directory, but if there is an error, it prints out an error message.
Let's have a look at the code.
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("-v", "--video", required = True, help = "Youtube video URL")
ap.add_argument("-a", "--audio", required = False, help = "Audio only", action = argparse.BooleanOptionalAction)
args = vars(ap.parse_args())
if args["audio"]:
YoutubeAudioDownload(args["video"])
else:
YoutubeVideoDownload(args["video"])
And we are done!
To test the code out if it actually works, type the following in the terminal.
# for audio
python main.py -a -v "[YouTube video URL]"
# for videos
python main.py -v "[YouTube video URL]"
The audio/video directory should have the necessary media downloaded.
Wrap up
In this article, we discussed how to easily download audio and video from Youtube, using the pytube library. We also used the argparse library to add arguments to the terminal so that we can download the media with shorthand and links to either the audio or video. I personally use this to download songs that I like, and it works perfectly.
Let’s connect: Twitter & LinkedIn
You can also check out my Youtube channel.
Happy coding! 😊
Top comments (18)
Getting this error
I tried running it inside venv and even on my system python.
Update: Fixed it by doing these timonweb.com/python/fixing-certifi... and restarting terminal
Glad you fixed it!
It's working but not on my local IDE (vs code). I have to use replit to run it so it is not downloading the file to my device.
Is there any way to run this on vscode ?
Hello, thanks for reading!
It actually works on my IDE (VSCode)
I don't know how but it is working.
Now I will make a tkinter gui to give this program an application like experience.
Do I have permission to use your code to make a gui ?
Yeah sure, you can go ahead.
If you also need me to collaborate, we can work on it together.
It's good to know you want to use something of mine, which is yours now 😅
Already done, you can check it now
YTdownloader
This looks nice! 👍
Checking it out now
please rate this app 😊
It is printing "Video downloaded!" but the folder where i want to install it is empty.
In case of Replit it actually create a folder of that name and add the file to it.
I've had a good bit of fun messing around with
pytube
for various projects but it's been a while, I'll have to check it out again - thanks for the tutorial!You are welcome!
The function calls in your main function are different than your definitions.
download_audio
is meant to beYoutubeAudioDownload
download
is meant to beYoutubeVideoDownload
Opps, thanks for pointing this out!
I have edited the code 😃
Thanks for sharing! really helpful!
You are welcome 🤗
I need exactly something like this in PHP, I have searched the web for any library but found non, Can anyone provide me with access to YouTube music API thanks.
Hopefully I find my way around it when I gets it