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.