Simple Python 3 youtube downloader

Download any video with Python on Youtube

So.... when going to work by train, I like to watch some youtube video's.

I just saw that Kalle Hallden, posted a new python development video... but the internet connection (4G) was not so good.

So I just created this small script to easily download youtube video's. I used pytube to do so.

"""
Author : Theo van der Sluijs
License: MIT
Version: 1.0
V-Date: 16 sept 2019
email: theo@vandersluijs.nl
installation:
create a folder called : youtube
install pytube: pip install pytube
run: python downtube.puy
just add one or multiple youtube id's
(multiple comma separated)
Have fun!
https://www.buymeacoffee.com/itheo
"""

from pytube import YouTube
import sys
import os


class DownTube:
    def __init__(self, folder: str = None):
        self.folder = folder
        self.what_folder()
        self.download()

    def youtube_list(self, youtube_ids):
        return youtube_ids.split(',')


    def what_folder(self):
        if self.folder is not None:
            cp = os.getcwd()
            folder = os.path.join(cp, self.folder)
            os.makedirs(folder, exist_ok=True)
            return True

        while True:
            self.folder = input("Where should I download : ")
            if self.folder is not None and self.folder != "":
                break

    def download(self):
        yes_now = ['y', 'n']
        while True:
            you_tube = input("Give me the youtube id('s)): ")
            if you_tube is not None and you_tube != "":
                list = self.youtube_list(you_tube)
                for l in list:
                    self.do_download(l)

            more = ""
            while more not in yes_now:
                more = input("Download another one [y/n] ")
                if more == 'n':
                    sys.exit()

        print('all done')

    def do_download(self, id: str = None):
        try:
            yt = YouTube(f"http://youtube.com/watch?v={id}")
            yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first().download(self.folder)
        except Exception as e:
            print(e)


if __name__ == '__main__':
    dt = DownTube('YouTube')

Grab the code on Gist

Use it, however you want. And do not forget to hit that Donate button! :-)

Did you find this article valuable?

Support Theo van der Sluijs by becoming a sponsor. Any amount is appreciated!