How do I download YouTube videos with Python 3 using Pytube?

Python 3, pytube 9.0.6 in Windows 10. 

pytube is a very easy to use, light-weight library that you can sue to download YouTube Videos.

Installation can be achieved in the terminal or command prompt with pip:

To download a video from YouTube you don’t really have to do much. So much so that you can get everything you need from the shell and be downloading a video in two lines of code.

In line 2 you can see that we have copied and pasted our YouTube url. You can either use the one in the Address Bar on the one that appears when you click “Share” on YouTube.

streams basically gathers a list of formats that the video will be in. first() calls the first video format in the list and download() obviously download the video.

But where is the video downloaded? If you are following along in the shell, then it will be saved in your python folder. If you are creating a script in a Python code, then it it will be saved in the same folder as the script.

You can also change the download location manually, like follows:

.download('c:/Users/sterling/Downloads')

Video Information

pytube also collects a whole host of information about the YouTube video. Let’s look as some main ones.

All the names are fairly self explanatory.

Streams

once you load the YouTube file information you have access to its streams or the list of formats the video comes in along with their associated data.

We can see a whole host of formats and resolutions here for the video. Some of them are also separated by video and audio format. This could come in handy if you wanted to download just an audio file.

Select the first and last format by changing the video.streams.all() to video.streams.first() and video.streams.last() respectively.

If you want to be more specific after viewing all() the formats you can select a format by it’s ‘itag’:

It is then a simple process to add .download() to this selection.

 

Filter

After creating the streams method you can then filter it. Here are a few examples:

Filter by 30 frames per second:

Filter by a resolution of 480p:

Filter Auido only:

A full list of filters can be found here.

You can all use multiple options in your filter:

 

An Example

Finally, lets look at a short example of how you might download a video on the shell:

In line 1 the YouTube method is called from pytube.

Next ask pytube to find our video and gather its information.

Then in line 3 we make a stream variable that filters our list to only videos with the extension *.mp4.

We then get the list to see which one we want. in line 4.

Being cheapskates we choose the lowest resolution by invoking he last() method.

Finally we download the 144p video in our chosen file location.

 

 

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *