Download YouTube Videos in Python With PyTube

download-youtube-videos-in-python

In this post, we will explore how to download YouTube videos in Python using the PyTube library. PyTube is a popular Python library that enables easy and efficient downloading of YouTube videos directly from the command line.

With PyTube, we can easily specify the resolution of the downloaded video, display thumbnail images, and print the video title. There are many other features you can play around like choosing the format of the downloaded video, whether it be 720p, 360p, 1080p, or any other available resolution, or selecting video or audio formats like mp4, mp3, etc.

After reading this post, you will have a basic understanding of how to build a simple YouTube video downloader in Python using the PyTube library.

Is It Legal to Download YouTube Videos?

No, it is generally not legal to download YouTube videos unless you have explicit permission from the owner of the video. YouTube’s terms of service explicitly prohibit users from downloading videos without the prior consent of the video creator.

Downloading copyrighted content without permission is illegal and can result in legal consequences. You can only download youtube videos if the download button is available that too inside the phone App. Youtube currently launch offline mode where you can save your desired video by clicking on the download button in the mobile app.

Note that in this tutorial I am going to download a video from my own YouTube channel for the demo purpose. If you like to see some latest Data Science projects, you can subscribe to that channel.

Install PyTube Library

Before you can start downloading YouTube videos in Python, you need to install the PyTube library. This library is available for free on GitHub and can be installed quickly with the pip package manager. Run the below command in cmd to install the library.

pip install pytube

Displaying thumbnail images

Once you have installed the PyTube library, you can start our youtube downloader code in Python. Before downloading the video let’s first see if we can fetch youtube thumbnail images or not. Below code is to display YouTube thumbnail image using Python:

# youtube downloader python script
from pytube import YouTube
import requests
from io import BytesIO
from PIL import Image

# paste the YouTube video URL here
url = "https://www.youtube.com/watch?v=iVN3qymOB4c"

# create a YouTube object and get the video thumbnail and title
youtube = YouTube(url)
# Get the URL of the video's thumbnail image from the YouTube object
thumbnail_url = youtube.thumbnail_url

# display the thumbnail image and title
response = requests.get(thumbnail_url)
img = Image.open(BytesIO(response.content))
img.show()

Here in this code:

  • We are using PIL (Python Imaging Library) module to open and display the thumbnail image
  • In line 11 we are creating an YouTube object named “youtube”. This object represents the video with the given URL. This object will be used to interact with the video.
  • In line 13 we are fetching the thumbnail image using GET request method. Now you can skip this line if you know the video id for your desired video. In that case, you can manually mention the thumbnail_url by following link: https://img.youtube.com/vi/<VIDEO_ID>/maxresdefault.jpg
  • Finally, in lines 16-18, we are displaying the image
Also Read:  Measure Function Execution Time in R

Show YouTube thumbnail in Jupyter Notebook

If you run the above code in jupyter notebook, you will notice that the image will show using any image viewer application, not inside jupyter notebook. Now if you want to plot that YouTube video thumbnail image inside jupyter notebook, you can run below code:

# Code to Display Youtube thumbnail in Python
from IPython.display import Image, display
from pytube import YouTube

# Get the URL of the video's thumbnail image from the YouTube object
thumbnail_url = youtube.thumbnail_url

display(Image(thumbnail_url))
code-to-display-youtube-thumbnail-in-python

Printing the video title

While downloading a YouTube video using PyTube, you can also extract the title of the video. PyTube provides an easy way to access the video title using the title attribute of the YouTube object. Let’s do it in the below code:

# youtube video title program in python
from pytube import YouTube
import requests
from io import BytesIO
from PIL import Image

# paste the YouTube video URL here
url = "https://www.youtube.com/watch?v=iVN3qymOB4c"

# create a YouTube object and get the video thumbnail and title
youtube = YouTube(url)
title = youtube.title

# Print the title of the video
print(title)

This code will print the title of the video to the console.

Create Calculator in python using tkinter

Understanding Stream Types

Before downloading video from YouTube using PyTube library, you should understand the concept of stream types.

  • A stream is a single audio or video track of a YouTube video that can be downloaded
  • A video may have multiple available streams, each with different formats, resolutions, and file sizes
  • PyTube provides a way to obtain a list of all available streams for a video and to filter the list by various properties such as resolution, file format, etc.

To extract all types of streams for a video, you can use the streams property of the YouTube object.

# Explore Stream Types to download youtube videos using python
from pytube import YouTube

# paste the YouTube video URL here
url = "https://www.youtube.com/watch?v=iVN3qymOB4c"

# create a YouTube object and get the list of available streams
youtube = YouTube(url)
streams = youtube.streams.all()

# Print all stream types
print(streams)
[<Stream: itag="17" mime_type="video/3gpp" res="144p" fps="8fps" vcodec="mp4v.20.3" acodec="mp4a.40.2" progressive="True" type="video">, <Stream: itag="18" mime_type="video/mp4" res="360p" fps="30fps" vcodec="avc1.42001E" acodec="mp4a.40.2" progressive="True" type="video">, <Stream: itag="22" mime_type="video/mp4" res="720p" fps="30fps" vcodec="avc1.64001F" acodec="mp4a.40.2" progressive="True" type="video">, <Stream: itag="136" mime_type="video/mp4" res="720p" fps="30fps" vcodec="avc1.64001f" progressive="False" type="video">, <Stream: itag="134" mime_type="video/mp4" res="360p" fps="30fps" vcodec="avc1.4d401e" progressive="False" type="video">, <Stream: itag="160" mime_type="video/mp4" res="144p" fps="30fps" vcodec="avc1.4d400c" progressive="False" type="video">, <Stream: itag="139" mime_type="audio/mp4" abr="48kbps" acodec="mp4a.40.5" progressive="False" type="audio">, <Stream: itag="140" mime_type="audio/mp4" abr="128kbps" acodec="mp4a.40.2" progressive="False" type="audio">, <Stream: itag="251" mime_type="audio/webm" abr="160kbps" acodec="opus" progressive="False" type="audio">]

You can count the total number of streams for this video by running len(streams) which is 9. Now let me explain some important properties of a stream:

  • itag – This is a unique identifier for a stream. You can see all the streams have different itag values
  • fps (int or None) – The number of frames per second in the video
  • progressive (bool) – A boolean parameter that excludes adaptive streams. It indicates whether one file contains both audio and video tracks or not
  • res (str or None) – The video resolution
  • vcodec (str or None) – The compression format used for the video
  • acodec (str or None) – The compression format used for the audio
  • mime_type (str or None) – The file format of the video. mp4, mp3, 3gp etc.
  • type (str or None) – The type of video, such as audio or video
Also Read:  6 Best Books to Learn Django with Learning Path

Check audio is available or not for all Resolution

While downloading YouTube videos you may find that for some resolution the video is muted. That means for that resolution audio is not available, let’s check that using Pytube and Python.

# Check audio availability of a YouTube video
from pytube import YouTube

# paste the YouTube video URL here
url = "https://www.youtube.com/watch?v=iVN3qymOB4c"

# create a YouTube object and get the video stream
youtube = YouTube(url)

preffered_resolution = ['144p', '240p', '360p', '480p', '720p', '1080p']

for resolution in preffered_resolution:
    video_streams = youtube.streams.filter(progressive=True, res=resolution)
    
    if len(video_streams) > 0:
        print(resolution)
    else:
        print(resolution + ' Audio is not available')
144p
240p Audio is not available
360p
480p Audio is not available
720p
1080p Audio is not available

Download Youtube Videos

Now that you understood all basic functionality of PyTube library like streams, print video titles and thumbnails, etc. We can now start the main part of this tutorial which is how to download youtube videos in Python using Pytube library. The below code is to do that.

# Download youtube videos in python using pytube library
from pytube import YouTube

# paste the YouTube video URL here
url = "https://www.youtube.com/watch?v=iVN3qymOB4c"

# create a YouTube object and get the video stream
youtube = YouTube(url)
video_streams = youtube.streams.filter(res="720p")
print(video_streams)

# set the download path and download the video
download_path = "C:/Users/Anindya/Downloads"
video_streams.first().download(download_path)
[<Stream: itag="22" mime_type="video/mp4" res="720p" fps="30fps" vcodec="avc1.64001F" acodec="mp4a.40.2" progressive="True" type="video">, <Stream: itag="136" mime_type="video/mp4" res="720p" fps="30fps" vcodec="avc1.64001f" progressive="False" type="video">]
'C:/Users/Anindya/Downloads\\Create Calculator in python using tkinter.mp4'

Here in this code in line 8-10 we are creating a YouTube object with the URL which is set earlier. Then we are using the streams.filter() method to filter for video streams for a resolution of 720p (as audio is not available for 1080p resolution). Now there can be multiple streams with the same resolutions. Then we are printing out all available video streams with that resolution. In line 14 we are downloading the first video stream from all available streams.

Also Read:  Python | List all files in a Directory

Now if you are facing error like below, that means the resolution you are trying to filter is not available in the stream. In this case you can try downloading/ filtering videos with different resolutions from the stream.

AttributeError: 'NoneType' object has no attribute 'download'

Downloading Only Audio

To download only the audio of a YouTube video using PyTube, you can use the filter() method to filter for streams that only contain audio. Then you can call the download() method on the first stream in the resulting list. Below code is to do this.

# Download youtube audio in python
from pytube import YouTube

# Set the URL of the video you want to download
url = "https://www.youtube.com/watch?v=iVN3qymOB4c"

# Create a YouTube object
yt = YouTube(url)

# Filter for streams that only contain audio
audio_streams = yt.streams.filter(only_audio=True)
print(audio_streams)

# set the download path and download the youtube audio
download_path = "C:/Users/Anindya/Downloads"

# Download the first stream in the list
audio_streams[0].download(download_path)

In this code, only_audio=True is used to filter for streams that only contain audio. The download() method is then called on the first stream in the list to download the audio stream.

Note that the downloaded video will be in the default format for audio streams, which is .mp4. If you want to convert the file to another audio format, such as .mp3, you will need to use a separate library or tool to perform the conversion.

Conclusion

In conclusion, PyTube is a powerful and easy-to-use Python library that allows you to download YouTube videos easily. By understanding the different stream types, we can customize our download to match the desired resolution, format, and quality. We can also display thumbnail images, print the video title, and even download video and audio streams separately.

In this post, I shared with you a basic youtube downloader python script. I have explained each functionality of the Pytube library of python. Whether you are a data scientist, developer, or just someone who wants to save a favorite video for offline viewing, PyTube is a great choice. So give it a try and see how easy it is to download YouTube videos in Python!

Leave a comment