How to Download YouTube Videos in Python

In this tutorial, we will learn how to download YouTube videos in two different ways using Python.

 

Download pytube

The first way to download a YouTube video is with pytube, which is a third-party Python package. For Python 3 type the following into the terminal to install it.

 

pip install pytube3

 

for Python 2.* install pytube like this:

 

pip install pytube

 

Import the pytube Package

Now that pytube has been installed it can be used in your program. It will need to be imported first like this:

 

import pytube

 

Create a New YouTube object

The next step is to create a new YouTube object. To do this, supply a YouTube video URL to the pytube.YouTube() method and store the result in a variable.

 

url = 'https://www.youtube.com/watch?v=-t1_ffaFXao'
youtube = pytube.YouTube(url)

 

Get the Video

Now we can extract the video to download from the YouTube object. YouTube keeps all videos in a variety of different resolutions and with pytube we can automatically select the highest resolution available or simply get the first stream (which might be lower in quality).

 

video = youtube.streams.first()
# or the best quality:
video = youtube.streams.get_highest_resolution()

 

Download the Video

Now we can download the video using the download() method, passing the path to where the file should be saved inside the () parenthesis.

 

video.download('videos')

 

Get Video Information

Information about the video such as its title, age restriction status, id .etc are available as properties of the video object. They can be accessed like this:

 

video.age_restricted
video.title
video.id

 

Download Age Restricted Videos

Some videos on YouTube are not allowed to be viewed until you log in. Unfortunately, pytube will not be able to download those videos, though they can be downloaded using a different YouTube video downloader package for Python called pafy

 

Install pafy

We will first need to install pafy using pip in the terminal.

 

pip install pafy

 

Import pafy

Now import pafy into your Python program.

 

import pafy

 

Download a Video with pafy

In the example below, we are creating a new pafy object with a YouTube video URL, getting the best video resolution and downloading it.

 

import pafy

url = 'https://www.youtube.com/watch?v=-t1_ffaFXao'
video = pafy.new(url)
best = video.getbest()
filename = best.download(filepath='videos/' + title + '.' + best.extension)

 

Conclusion

You now know two different ways to download YouTube videos in Python. The above examples demonstrate how to use the pytube and pafy packages to get and download a video though in most cases this will just be one function in a class that has more functionality.

video download