How to download YouTube Videos using Python

Spandan Sehgal - Dec 21 '21 - - Dev Community

Intro

Hello everyone I hope you are doing well.
In this post, as you read the title we are going to make a YouTube video downloader in Python it is a very simple and fun project to build.

Modules needed :-

1) pytube :- it is an module which lets us access YouTube content from python

Installation :-

pip install pytube

Let's Code

First we will import the module which we installed

#Importing the required modules
import pytube
Enter fullscreen mode Exit fullscreen mode

Now we will ask the user for entering the link of the video and a path where he/she has to save the video

#Asking for the link
link = input("Enter the link:\n ")

#Asking for the save location
save_path = input("Enter the path to save the video: ")
Enter fullscreen mode Exit fullscreen mode

Now we will download the video and save it to the provided location

#Downloading the video with .mp4 extension to the save location
yt = pytube.YouTube(link)
stream = yt.streams.filter(file_extension='mp4').first()
stream.download(save_path)
Enter fullscreen mode Exit fullscreen mode

In the line yt.streams.filter(file_extension='mp4').first() we can define in which format we want to save the file, so in most cases .mp4 extension is the best.

And with that done we have successfully created our project.
I hope you all enjoyed the post.
Stay safe and do take very good care of yourselves!

Feel free to ask doubts or suggest me something that I can build in next post or anything I can add in this project.

Happy Coding !

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .