Python Script to Download YouTube Videos With Examples

We can use pytube Python library to download YouTube videos. It’s a simple and lightweight Python module with no third-party dependencies.

Installing pytube Library

If you look at the PyPI, there are two types of pytube libraries: pytube and pytube3. When I installed pytube library, I got error in importing its YouTube class.

I didn’t faced any issues with pytube3 library.

So, I would recommend you to use pytube3 library. I am using the same in this tutorial.

Python Script to Download a YouTube Video

The first step is to import the YouTube class from the pytube module.

Next step is to create the YouTube object by passing the YouTube video URL.

The YouTube object opens different streams from the YouTube video URL. We can get all the stream information using the following code.

It will produce the following output.

Few important Points:

  • The “progressive” stream contains the file having both audio and video.
  • The “adaptive” stream contains either audio or video.
  • The “mime_type”, “res”, and “fps” attributes can be used to filter the stream that we want to download.

We can use the filter() function to extract only specific streams. This is useful when we want to download all the different resolutions of the YouTube video.

Output:

There are few useful functions to get the highest and lowest resolution videos.

The final step is to call the download() method on the specific stream to download the YouTube video.

The video will be downloaded in the current working directory. The video file name will be the title of the YouTube video.

Complete Code to Download the Highest Resolution YouTube video

Specifying the Downloaded YouTube Video File Location and Name

The download() function accepts different parameters to change the video file location and name.

Downloading Only Audio from the YouTube Video URL

Sometimes we want only the audio from the YouTube video URL. We can use the get_audio_only() function for this.

Getting YouTube Video Metadata Information

We can also get the YouTube video metadata information such as title, description, video length, rating, author name, views count, etc.

Downloading Multiple YouTube Videos

If you have to download multiple videos, we can extend the program easily.

If you are specifying the filename and directory parameters in the download() function, make sure they are different for each video to avoid overriding.

Downloading All the Videos from a YouTube Playlist

We can use the Playlist class to download all the videos from a YouTube playlist.

Conclusion

Python pytube library is simple and powerful. We can download YouTube videos in different resolutions, only audio, and all the videos from a playlist.

Reference: PyPI pytube3 page

By admin

Leave a Reply