[python]Download videos from youtube with pytube

Introduction

I am finding a windows application which can use to download youtube videos like downie, I found out a python module known as pytube3 that can be used for this purpose.

Basic usage

So for my own purpose I download some videos which I need to listen while exercising, below is the code to use the module.

from pytube import Playlist, YouTube
from pytube.cli import on_progress
from pathlib import Path
from os.path import join


def get_yt_playlist(playlist=None):
    """
    Get the list of youtube urls. Playlist can be used to download playlist as well,
    but there is no on_progress_callback hence I cannot get the progress bar for each videos.
    :param playlist: 
        This is the url of the youtube playlist.
    :return: 
        list of playlist urls.
    """
    pl = Playlist(playlist)
    return [l for l in pl]


def download_vid(url=None, path=None):
    """
    This function downloads the video from each playlist url,
    the path is specified with the path keyword.
    :param url: 
        youtube url
    :param path: 
        path to save the video in your computer
    :return: 
        None
    """
    # on_progress is a progress bar in the pytube3 module.
    # the progress bar is shown in sys.stdout.
    yt = YouTube(url, on_progress_callback=on_progress)
    stream = yt.streams.first()
    # video title
    print(stream.title)
    # download and save to the computer path.
    stream.download(path)


if __name__ == "__main__":
    """
    This is an example using a youtube playlist.
    I tried threading, but youtube will reset the connection.
    So for this example is download one video after video finished, 
    which is very slow.
    """
    playlist = "https://www.youtube.com/playlist?list=PLxak_2LR4viU1-f6BkNlqudd_WXAecDX_"
    collect_list = get_yt_playlist(playlist)
    path = join(str(Path.home()), "Downloads", "仙逆")
    for pl in collect_list:
        download_vid(url=pl, path=path)

This is how the progress bar looks like with on_progress function from pytube3.
bar1, of course I can write a function to update the progress of a video title, but I still do not know how to integrate with threading, if you have got an example that uses pytube3 with threading with progress bar for each videos let me know below.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s