Download YouTube Videos with Python - Part 1

Download YouTube Videos with Python - Part 1

I love watching YouTube videos and chances are you would too. But sometimes you would want to download YouTube videos because you would want to listen to songs in a road trip or watch a clip from your favourite TV show. Today, I will show you how to automate YouTube downloads with Python.

We will be exploring a module called Pytube. Pytube is a simple Python library which allows you to download single or multiple YouTube videos in different formats.

So to get started install the Pytube library via pip. Run pip install pytube command to install the library in your project directory. Create a file with the name, download.py. Now open the file in your favourite code editor.

Start by adding this piece of code in it.

from pytube import YouTube

path_to_save = "/⁨Users/{your_username}/Downloads"
video_link = "https://www.youtube.com/watch?v=eB0nUzAI7M8"

youtube = YouTube(video_link) 
mp4videos = youtube.filter('mp4') 
youtube.set_filename('My video')
video = youtube.get(mp4videos[-1].extension, mp4videos[-1].resolution) 
video.download(path_to_save)

This is all the code we need to start downloading videos from YouTube. Let's walk through this together. The first line is the import statement where we import YouTube from pytube. In the second line of code we just declare the variable which contains the path of the folder where we will save the video. You can change it to wherever you want to save the video. The third line of code is also a variable where we are setting the video link. The fourth line is where we are creating a YouTube object in which we are passing video_link as a parameter. In the fifth line, we use the filter method on the YouTube object to filter out the videos that are not mp4. We then use set_filename method on the YouTube object to set the name of the video which we are downloading. The last two lines basically, create a variable and then download the video. The variable created stores a specific video which we get through the get method. The get method takes two arguments, the extension and the resolution. We can get the extension and the resolution of the mp4 videos using the extension and resolution properties respectively. Lastly, the download method downloads the video to the path where you save the video.

After running the script, the video should successfully be downloaded to the path. Now you can sit back and relax while your videos download. In the next post, I will show you how to download multiple YouTube videos with the Pytube library. If you found this post useful then react to it and comment down below with YouTube videos you downloaded with this script. Thank you for reading and I will see you in the next post which will be even more exciting.

P.S. - Do you like this way of posts where I create bite-sized posts and divide it into series or one big post? Comment down below with your preference.