avatarStackZero

Summary

The web content provides a tutorial on creating a YouTube downloader using Python, which includes features for downloading single videos, entire playlists, and displaying a progress bar.

Abstract

The article introduces a Python-based project aimed at beginners interested in learning Python through practical application. It guides readers through building a YouTube downloader with functionalities such as downloading individual videos with stream selection, downloading entire playlists with the highest resolution available, and displaying a progress bar during downloads. The tutorial emphasizes the use of the pytube library for YouTube interactions and the click library for command-line interface (CLI) management. It also touches on the benefits of type hinting in Python for error prevention and IDE autocompletion. The author encourages readers to engage with the code, offering suggestions for further improvements and inviting them to explore more advanced projects in cybersecurity.

Opinions

  • The author believes that learning Python can be enjoyable and practical, as demonstrated by the YouTube downloader project.
  • The use of pytube and click libraries is highly recommended by the author for their simplicity and effectiveness in handling YouTube interactions and CLI options.
  • Type hinting is presented as a valuable feature in Python for enhancing code reliability and developer experience.
  • The author expresses a commitment to supporting newcomers to coding and cybersecurity, suggesting that a coder's mindset is crucial even in security-focused roles.
  • The article concludes with an invitation to readers to expand the project with additional features and to explore other beginner-friendly cybersecurity projects suggested by the author.

Introducing The Simple Way To Make You Creating a Youtube Downloader With Python

Photo by Christian Wiediger on Unsplash

Introduction

Hi guys, here is another tutorial for Python beginners! I wanna show you again how learning python can be funny.

In this tutorial we are going to see the simplest way to create a basic YoutubeDownloader with these features:

  • Download a single video from the given URL
  • Allow you to choose the stream when downloading a single video.
  • Download a full playlist by getting the higher resolution videos.
  • Show a progress bar during the download

I hope I have intrigued you with this brief presentation, so let’s code together!

Step #1: Import all the libraries

Before starting to write the actual code we need to import the following libraries:

  • pytube: it’s in charge of managing all our interactions with Youtube
  • click: that’s my favorite library for handling command line arguments and options

We can install them with the following commands on the terminal:

pip install pytube
pip install click

Now we can finally import everything we need:

import click
import pytube
from pytube.cli import on_progress
from typing import List

I also introduced hint typing just to show you a nice feature introduced recently in python 3.

It consists in type declaration and can be useful to:

  • Prevent errors
  • Use autocompletion in your IDE in your functions

Step #2: Define the auxiliary functions

There is not so much to do in this step.

In the case of downloading a single video, we want to print all the streams (there are different versions we can download).

Having all the information about the existing streams we can choose the one we want to download by its tag.

So let’s see the code of the function which prints the necessary information about every stream in a given list.

def print_streams(streams: List[pytube.Stream]):
    for stream in streams:
        print(f"itag={stream.itag} mime_type={stream.mime_type} "
              f"res={stream.resolution} fps={stream.fps} "
              f"vcodec={stream.video_codec} " 
              f"acodec={stream.audio_codec} type={stream.type}>\n")

It simply loops through the list and prints all the information for each stream on the screen

So this step is complete, now let’s use click to define our CLI options!

Step #3: Handle CLI Options with click library

The library we are going to use makes our work extremely simple. We essentially need two parameters:

  • The Youtube URL
  • A flag that tells us if we are downloading a playlist

This is the code:

@click.command()
@click.option('-U','--url', help='The url of the YT video', required=True)
@click.option('-P','--playlist', is_flag = True, default=False, help='The url of the playlist')

The parameters define how to call the option on the command line, if it’s a flag and the response to the help option. Obviously the decorators have to be above the main function.

Step #3: The main function

We finally got to the logic of the program, we have the main function which has as parameters the ones defined as options with the click library.

The function is divided into two main blocks:

  • Download video
  • Download playlist

This is the first block: “Download a single video”

yt = pytube.YouTube(url, on_progress_callback=on_progress)
        streams = yt.streams.filter(progressive=True)
        print_streams(streams)
        itag = input("Please choose the video you want to download: ")
        yt.streams.get_by_itag(int(itag)).download()

But what is this code doing ?

  • Creates a Youtube object, initialized with the given URL, and sets the default pytube progress bar as on_progress callback
  • Filters all the progressive streams ( the ones with video and audio in a single file)
  • Prints all the filtered streams
  • Asks the user to choose the stream by its itag
  • Downloads the selected stream

That’s all, so let’s see the block related to the playlist download:

pl = pytube.Playlist(url)
        for video_url in pl.video_urls:
            yt = pytube.YouTube(video_url,
                 on_progress_callback=on_progress)
            streams = yt.streams.filter(progressive=True)
            print(f"Downloading: {yt.title}")
            streams.get_highest_resolution().download()
            print("\n")

And this is the description step by step of this code.

  • Creates a Playlist object with the URL from the command line
  • Iterates all the videos inside the playlist

Then for every video it:

  • Filters the progressive streams as in the previous block
  • Prints the title
  • Downloads the highest resolution video

Now, before concluding I guess you want to see the full code of our mini project:

Let’s imagine we saved our source into a file called “main.py”, if we want to use our Youtube Downloader, just open a terminal into the directory where is the file and type:

python3 main.py --url <YOUTUBE_VIDEO_URL>

For downloading the video, and if you want to download a playlist you can do just by typing:

python3 main.py -P --url <YOUTUBE_PLAYLIST_URL>

Maybe you can have problems with your URL, and if it happens, try to put it in quotes.

Conclusion

As you can see, even learning can be funny. I hope you enjoyed this mini project and I’m looking forward to proposing more.

You can see from my blog (StackZero) and my medium page I deal mainly with security.

But still, I am convinced that a coder’s mindset is essential in this field as well, so I will do everything I can to help anyone who wants to get into this amazing world!

That’s why I started to make some practical tutorials for beginners.

I want to conclude with some suggestions for improving this project and learning more.

  • Give the user the possibility to choose the stream even with playlists
  • Handle the exceptions (for example a non-existent URL)
  • Print the title when downloading a single video
  • Make a GUI as we’ve seen in this post
  • Give the user the possibility to download from many playlists (maybe from a file)

There is so much you can do, anyway I invite you to consider trying some projects on cybersecurity, I did something beginner-friendly:

Thank you for your time, I hope to see you soon!

Python
Python Programming
Learning To Code
Beginner Coding
Python3
Recommended from ReadMedium