Skip to content

Instantly share code, notes, and snippets.

@tripulse
Last active April 6, 2020 11:51
Show Gist options
  • Save tripulse/e319d24bbc7b8b48f73336f7bc230e0c to your computer and use it in GitHub Desktop.
Save tripulse/e319d24bbc7b8b48f73336f7bc230e0c to your computer and use it in GitHub Desktop.
A script to download thumbnails of YouTube videos.
#!/usr/bin/env python
"""
yt-thumb: a script to download thumbnails of YouTube videos of quantized set
of qualities (lowest, low, mid, high, highest). This tool nor the method it
uses imposes any restrictions on downloading thumbnails.
Qualities and their co-respoding width, height dimensions:
* lowest 120x90
* low 320x180
* mid 480x360
* high 640x480
* highest 1280x720
"""
import re
from urllib.request import urlopen
from urllib.error import URLError
from argparse import ArgumentParser, FileType, RawTextHelpFormatter
from functools import partial
from sys import stdout
from shutil import copyfileobj
def extract_id_from_url(url: str):
# Stripped version of the RegEx:
# https://github.com/ytdl-org/youtube-dl/blob/master/youtube_dl/extractor/youtube.py#L372-L427
return re.compile(r"""(?x)^(
(?:https?://|//)
(?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie|kids)?\.com/|
(?:www\.)?deturl\.com/www\.youtube\.com/|
(?:www\.)?pwnyoutube\.com/|
(?:www\.)?hooktube\.com/|
(?:www\.)?yourepeat\.com/|
youtube\.googleapis\.com/)
(?:.*?\#/)?(?:(?:(?:v|embed|e)/(?!videoseries))|(?:(?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)?(?:\?|\#!?)(?:.*?[&;])??v=)))
|(?:youtu\.be|vid\.plus|zwearz\.com/watch|)/|(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=))?
(?P<id>[0-9A-Za-z_-]{11})(?!.*?\blist=(?:([0-9A-Za-z_-]{34})|WL))(?(1).+)?$""").match(url).groupdict().get('id')
class YouTubeThumbnailGrabber(ArgumentParser):
Q2T = { 'highest': 'maxresdefault',
'high' : 'sddefault',
'med' : 'hqdefault',
'low' : 'mqdefault',
'lowest' : 'default', }
def __init__(self):
ArgumentParser.__init__(self,
description= __doc__,
formatter_class= RawTextHelpFormatter)
self.add_argument('URL',
help= "YouTube-like video URL to grab (eg. 'youtu.be').")
self.add_argument('OUT',
nargs= '?',
default= stdout.buffer,
help= "output path of the downloaded thumbnail.\n"
"Tip: place '%%s' to replace with video ID.")
self.add_argument('-q',
default= '/'.join(self.Q2T.keys()),
dest= 'qualities',
choices= self.Q2T.keys(),
help= "quality scale of the thumbnail.")
self.args = self.parse_args()
def main(self):
video_id = extract_id_from_url(self.args.URL)
for imgq in self.args.qualities.split('/'):
try:
img = urlopen(f'https://i1.ytimg.com/vi_webp/{video_id}/{self.Q2T[imgq]}.webp')
copyfileobj(img, open(self.args.OUT % video_id, 'wb') \
if isinstance(self.args.OUT, str) else self.args.OUT)
break
except URLError:
print(f'ERROR: {imgq} quality for video not found!'); continue
if __name__ == "__main__":
YouTubeThumbnailGrabber().main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment