Python Forum
YouTube Video Downloader - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: Code sharing (https://python-forum.io/forum-5.html)
+--- Thread: YouTube Video Downloader (/thread-33829.html)



YouTube Video Downloader - BlazingWarlord - May-31-2021

YouTube Video Downloader

A simple YouTube video downloader that uses Pytube and google-search-module to accept a keyword and download the video most related to that keyword (according to Google Search Results). Share it with others if you like it.


RE: YouTube Video Downloader - DeaD_EyE - May-31-2021

Improved version

#!/usr/bin/env python3

"""
Program to search and download YouTube videos
"""

from argparse import ArgumentParser
from pathlib import Path

try:
    from googlesearch import search
    from pytube import YouTube
    from pytube.exceptions import PytubeError
except ImportError:
    raise SystemExit("pip3 install googlesearch-python pytube")


def download_yt(search_term, amount):
    for link in search(f"{search_term} site=youtube.com", num_results=amount):

        yt = YouTube(link)

        try:
            video = yt.streams[0]
        except PytubeError:
            print("Skipping", link)
            continue

        if Path(video.default_filename).exists():
            print(video.default_filename, "exists, skipping...")
            continue

        try:
            video.download()
        except PytubeError:
            print("Could not download", link)
            continue
        else:
            print(f"{video.default_filename} downloaded")


def get_args():
    parser = ArgumentParser(description="Search videos on youtube and download them")
    parser.add_argument("search", help="Search term")
    parser.add_argument("amount", type=int, help="Amount of results")
    return parser.parse_args()


if __name__ == "__main__":
    args = get_args()
    try:
        download_yt(args.search, args.amount)
    except Exception as e:
        print("Bug in program")
What I dislike, is the fact that I get sometimes channels and not videos.
Maybe there is a better googlesearch or a module, which can search videos on yt.