Download YouTube videos in Python

    We can use the package Pytube to download YouTube videos in a Python script. It’s a free tool you can install from the PyPI repository. You can also specify the output format (eg: mp4) and resolution (eg: 720px) when downloading videos.

    Here’s a step-by-step approach to downloading YouTube videos in Python.

Step I: Install Pytube using pip

pip install pytube

Step II : In your script import the YouTube class from pytube package.

from pytube import YouTube

Step III : Create an object of YouTube bypassing the video URL

yt = YouTube("<Your youtube URL>")

Step IV : Use the filter method to specify the download format of the video

mp4_files = yt.streams.filter(file_extension="mp4")

Step V : Get the video you want by specifying the resolution

mp4_369p_files = mp4_files.get_by_resolution("360p")

Step VI : Save the downloaded video to the local file system

mp4_369p_files.download("<Download folder path>")

Here’s what the completed script will look like. I’ve wrapped it with a function definition that accepts the url and outpath as arguments.


The above code will download the Spiderman: No way home trailer and save it in a folder called ‘trailers’.

Disqus Comments

Download YouTube videos in Python

     We can use the package Pytube to download YouTube videos in a Python script. It’s a free tool you can install from the PyPI repository....