YouTube has become the go-to source for videos on the internet. While there are many ways to download YouTube videos, using Python is one of the easiest. In this article, we will show you how to use Python to download YouTube videos.
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 (e.g., mp4) and resolution (e.g., 720px) when downloading videos.
If you’re looking for more interesting applications of Python programming, checkout, Automate the Boring Stuff with Python.
Downloading YouTube Videos in Python
Here’s a step-by-step approach to downloading YouTube videos in Python.
Step I: Install Pytube using pip
Step II: In your script, import the YouTube class from pytube package.
Step III: Create an object of YouTube bypassing the video URL
Step IV: Use the filter method to specify the download format of the video
Step V: Get the video you want by specifying the resolution
Step VI: Save the downloaded video to the local file system
Here’s what the completed script will look like. I’ve wrapped it with a function definition that accepts the URL and output path as arguments.
The above code will download the Spiderman: No way home trailer and save it in a folder called ‘trailers’.
Creating a CLI to download more videos in the command prompt.
Now we converted our function into a command line interface that accepts a URL parameter and saves the video into the local filesystem. Here’s how to run this.
Not a Medium member yet? Please use this link to become a member because I earn a commission for referring at no extra cost for you.