How to Download YouTube Videos Using Python Scripts

In this tutorial, we will understand how to download YouTube videos using the Python script. As we know that Python has many features, extensive modules and libraries is one of them. We will use one popular pytube library and write the Python script.

YouTube is a very popular online video streaming platform. There are millions of videos from various categories such as education, entertainment, travel, etc. We can easily watch the videos that we want to with simple clicks, but downloading videos is tough. However, in the recent update, YouTube allows us to save the videos in its download folder that can play offline. But we cannot save them locally.

Many third-party websites are available that fetches the videos and save them on the local computer or mobile phone. We can simplify the process using Python. It will take a few lines of code, and the desired video can be downloaded easily. Let's see the implementation of the pytube library in Python.

The pytube Library

The pytube is a third-party, lightweight, Pythonic; dependency-free module used for downloading YouTube videos. Hence, it is not a native library, we need to install first before using it.

Type the following command in your terminal or command prompt.

Command

After hitting enter, above command will download the packages to local system.

Note - We recommend you to install this library in virtual environment.

Download Single Video using Pytube Library

Pytube has made the download YouTube videos very easily. First, we import the YouTube class from the pytube module.

Now we create the object of the YouTube class by passing the link as the parameter.

This youtube_obj creates the various streams from the YouTube video URL. Using the below code, we can get all the stream information.

Then get the proper extension and resolution of the video. After doing this, we will use the download() method that takes the one parameter, a file download location.

We can provide the file as our suitability; the original name will be kept in another case.

Now implement the complete code. Let's understand the following code.

Example -

Output:

Task is Completed    

The above code will take some time to download the file as a lot of data is being downloaded from the web. The connection speed is also dependent on the downloading speed. We can also download multiple videos.

Fetch Video Title

We can fetch the title of the video to be downloaded using the below code.

Output:

Shamshera | Date Announcement Teaser | Ranbir Kapoor, Sanjay Dutt, Vaani Kapoor | In Cinemas 22 July 

And following how we would get the thumbnail url.

Output:

https://i.ytimg.com/vi/oQdxL_WW3aE/sddefault.jpg    

Advance Way to Create YouTube Object

The YouTube object is essential to move further in the pytube programming. Earlier, we discussed how to create a simple object, and now we will move on to create a YouTube object with more properties. Let's see the following example.

Example -

Properties -

  • on_process_callback - This function is used for downloading chunks from a video, and it takes three parameters: the data chunks and the bytes remaining in the video.
  • on_complete_callback - This function will execute when the video is fully downloaded. It can be used in post-download operations like trimming the length of the video. It takes two arguments - the stream and file path.
  • use_oauth and allow_oauth_cache - This allows us to authorize pytube to interact with the YouTube user account. It also can be used to bypass age restrictions.

Subtitle/Caption Tracks

Pytube provides the facility to get the available captions. Let's see the following snippet.

Example -

Output:

{'ar': <Caption lang="Arabic" code="ar">, 'zh-HK': <Caption lang="Chinese (Hong Kong)" code="zh-HK">, 'zh-TW': <Caption lang="Chinese (Taiwan)" code="zh-TW">, 'hr': <Caption lang="Croatian" code="hr">, 'cs': <Caption lang="Czech" code="cs">, 'da': <Caption lang="Danish" code="da">, 'nl': <Caption lang="Dutch" code="nl">, 'en': <Caption lang="English" code="en">, 'en-GB': <Caption lang="English (United Kingdom)" code="en-GB">, 'et': <Caption lang="Estonian" code="et">, 'fil': <Caption lang="Filipino" code="fil">, 'fi': <Caption lang="Finnish" code="fi">, 'fr-CA': <Caption lang="French (Canada)" code="fr-CA">, 'fr-FR': <Caption lang="French (France)" code="fr-FR">, 'de': <Caption lang="German" code="de">, 'el': <Caption lang="Greek" code="el">, 'iw': <Caption lang="Hebrew" code="iw">, 'hu': <Caption lang="Hungarian" code="hu">, 'id': <Caption lang="Indonesian" code="id">, 'it': <Caption lang="Italian" code="it">, 'ja': <Caption lang="Japanese" code="ja">, 'ko': <Caption lang="Korean" code="ko">, 'lv': <Caption lang="Latvian" code="lv">, 'lt': <Caption lang="Lithuanian" code="lt">, 'ms': <Caption lang="Malay" code="ms">, 'no': <Caption lang="Norwegian" 
code="no">, 'pl': <Caption lang="Polish" code="pl">, 'pt-BR': <Caption lang="Portuguese (Brazil)" code="pt-BR">, 'pt-PT': <Caption lang="Portuguese (Portugal)" code="pt-PT">, 'ro': <Caption lang="Romanian" code="ro">, 'ru': <Caption lang="Russian" code="ru">, 'sk': <Caption lang="Slovak" code="sk">, 'es-419': <Caption lang="Spanish (Latin America)" code="es-419">, 'es-ES': <Caption lang="Spanish (Spain)" code="es-ES">, 'sv': <Caption 
lang="Swedish" code="sv">, 'th': <Caption lang="Thai" code="th">, 'tr': <Caption lang="Turkish" code="tr">, 'uk': <Caption lang="Ukrainian" code="uk">, 'ur': <Caption lang="Urdu" code="ur">, 'vi': <Caption lang="Vietnamese" code="vi">}

Now, we will get the English captions.

Output:

<stdin>:1: DeprecationWarning: Call to deprecated function get_by_language_code (This object can be treated as a dictionary, i.e. captions['en']).

Let's see the format of the caption.

Output:

<?xml version="1.0" encoding="utf-8" ?><timedtext format="3">\n<body>\n<p t="10200" d="940">K-pop!</p>\n<p t="13400" d="2800">That is so awkward 
to watch.</p>\n<p t="16200" d="2080">YouTube Rewind 2018.</p>\n<p t="18480" d="3520">The most disliked video\nin the history of YouTube.</p>\n<p t="22780" d="2220">In 2018, we made something\nyou didn?t like.</p>\n<p t="25100" d="2470">So in 2019, let?s see what\nyou DID like.</p>\n<p t="27580" d="1400">Because you?re better at this\nthan we are.</p>\n<p t="45110" d="1310">This is my outfit!</p>\n<p t="46920" d="1240">What is it gonna be?</p>\n<p t="58180" d="1370">You made these the</p>\n<p t="59710" d="1680">MOST LIKED CREATOR VIDEOS\n*of 2019, duh?</p>\n<p t="62480" d="1700">Shane Dawson | Conspiracy Theories with Shane Dawson\n1.9M</p>\n<p t="65000" d="2690">A4 | ??????? ??? ??? ?? ?????? ?????? ?? ???????? !\n2M</p>\n<p t="67690" d="2750">Andymation | My BIGGEST Flipbook EVER\n2.3M</p>\n<p t="70930" d="1730">James Charles | No More Lies\n2.4M</p>\n<p t="73070" d="2030">SethEverman | how to create billie eilish?s ?bad guy?\n2.8M</p>\n<p t="76010" d="2300">Nilson Izaias Papinho Oficial | Minha slime deu 
certo\n2.8M</p>\n<p t="79290" d="2540">Black Gryph0n | ONE GUY, 54 VOICES\n3.4M</p>\n<p t="82650" d="2380">whinderssonnunes | O DIA EM QUE ASSISTI BIRD BOX\n3.4M</p>\n<p t="86290" d="2630">PewDiePie | Marzia & Felix - Wedding\n4.7M</p>\n<p t="89890" d="3530">MrBeast | Make This Video the Most Liked Video On YouTube\n10.9M</p>\n<p t="99150" d="2410">The MOST LIKED\nMUSIC VIDEOS</p>??.

We have taken the sample output; hence it consists of many lines in the format.

Download Multiple Videos

It is the same process as we use while downloading a single video. We can create a list with multiple URLs and iterate using for loop. Let's understand the following example.

Example -

The loop will pick one link at a time and pass it to the YouTube class to create an object. We passed a resolution in the get() function and saved the value in the desired location. Then, we filtered out all the files with the mp4 extension.

Python Search Features

Pytube allows us to perform search functionality same as we do in the YouTube using the searching bar. It can provide YouTube objects that can be inspected and downloaded instead of needing to do additional processing. Let's understand the following example.

Example -

Output:

[<pytube.__main__.YouTube object: videoId=AFEZzf9_EHk>, <pytube.__main__.YouTube object: videoId=_PNIlJry8vA>, <pytube.__main__.YouTube object: videoId=MFI-r7_xH-Y>, <pytube.__main__.YouTube object: videoId=mEOBGY4-7JA>, <pytube.__main__.YouTube object: videoId=n7xSITvP4D4>, <pytube.__main__.YouTube object: videoId=A5OU6YP3Jm4>, <pytube.__main__.YouTube object: videoId=Kwu1yIC-ssg>, <pytube.__main__.YouTube object: videoId=lA2Ojyb0gqg>, <pytube.__main__.YouTube object: videoId=gkWHGy70jIg>, <pytube.__main__.YouTube object: videoId=amMJfaB5dXo>, <pytube.__main__.YouTube object: 
videoId=rl3L2SGgmNo>, <pytube.__main__.YouTube object: videoId=AVbfs0-509k>, <pytube.__main__.YouTube object: videoId=Wi2oqXS6SlY>, <pytube.__main__.YouTube object: videoId=HNXhdo5j914>, <pytube.__main__.YouTube object: videoId=gmVj3yOdOFo>, <pytube.__main__.YouTube object: videoId=WUODHf0IT5U>, <pytube.__main__.YouTube object: videoId=mUniRe7tysE>, <pytube.__main__.YouTube object: videoId=ynG6tkLO3SQ>]

Searches also have associated autocomplete suggestions. These can be accessed below.

Output:

['2000 world cup final', '1999 world cup final', '2003 world cup final', '1996 world cup india vs pakistan', 'india vs pakistan champions trophy 2017 highlights', 'india vs australia 2011 world cup highlights', 'icc world cup 2021', 'icc world cup 2019 song', 't20 world cup 2016 final']   

Points to be remembered

  • To download the videos, you must have the proper internet connection. Otherwise, it will raise an error.
  • We can change the file's name using another array of the names.
  • Improper internet connection will stop the download and raise an error.

Conclusion

In this tutorial, we have covered the pytube library and its use cases. It is the best way to download YouTube videos without visiting any websites. Video downloading sites might take a lot of time and show many irrelevant advertisements. In Python, with a few lines of code, we can download single or multiple videos without any interruption. However, it would good if you had the proper internet connection. This library also consists of many advanced features, but we have mentioned all the important features. If you want to read more about the pytube library, you can visit its official well-written documentation.






Latest Courses