Have you ever wondered how the YouTube online video downloader works? How does the website manage to download a YouTube video from a URL?
In this tutorial, we will learn how to download a YouTube video using Python.
To run this code you can use any Python IDE. 10 reasons why VScode is better. For this tutorial, I will be using Google Colabs which is similar to Jupyter Notebook but cloud-based so you can execute and save your code online.
Let's start coding out Python YouTube downloader.
Install the pytube library
pytube is a lightweight, Pythonic, dependency-free, library (and command-line utility) for downloading YouTube Videos.
you can download the library using the pip command
pip install pytube
After installation, you will see the following output on colab notebook.
Make the video object
To make the video object use the following code. To make the video object video URL is required you can hardcode the URL in the script or in this case I have used the input function to get the URL as input after the program is run. The get_hightest_resultion automatically selects the highest resolution available.
P.S. You can check the resolution and other details of the video by printing the video_object by using print(video_output).
The output of video_object looks like this.
Call the download() fucntion
In the below code, I have used try and except error handling to catch any error while downloading the video.
Run the program and enter the video URL.
You can copy-paste any YouTube video URL into the input and it enter.
Play the output
You can find the downloaded video in the same folder of the script or in my case you can find the downloaded video in Google Colabs file-explorer pane on the left.
You can download the video by double-clicking on the file.
Well, you might ask does it also downloads YouTube short video?
The answer is YES it can download YouTube short videos also. Give it a try use the same colab notebook here.
Thanks for reading the tutorial, if you find this tutorial please like and leave a comment in the comment section.
And always, stay healthy, be curious and make the world a better place.