Skip to content

Instantly share code, notes, and snippets.

@rmoch
Forked from mlorant/get_thumbnail.py
Created March 31, 2013 20:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmoch/5281840 to your computer and use it in GitHub Desktop.
Save rmoch/5281840 to your computer and use it in GitHub Desktop.
import re
# List of format available on Youtube
YOUTUBE_CHOICES = ("default", "hqdefault", "0", "1", "2")
# Default image if no thumbnail is found
NO_PREVIEW = "/static/img/no_preview.png"
def get_video_thumbnail(url, version="hqdefault"):
"""
Get a thumbnail of a video from Youtube/Dailymotion, via
its watch link. This function extract the video ID from
the link given and put it in a pre-made link which returns
the thumbnail.
"""
# Youtube case
if 'youtu' in url:
# All credits to http://stackoverflow.com/a/4811367/1433392 for the regex
m = re.search(r"^.*(youtu.be\/|v\/|embed\/|watch\?|youtube.com\/user\/[^#]*#([^\/]*?\/)*)\??v?=?([^#\&\?]*).*", url)
if m and version in YOUTUBE_CHOICES:
return "http://img.youtube.com/vi/%s/%s.jpg" % (m.group(3), version)
else:
return NO_PREVIEW
# Dailymotion
elif 'daily' in url:
m = re.search(r"^.+dailymotion.com\/(video|hub)\/([^_]+)[^#]*(#video=([^_&]+))?", url)
if m:
return "http://www.dailymotion.com/thumbnail/video/%s" % m.group(2)
else:
return NO_PREVIEW
else:
return NO_PREVIEW
# Tests, just print stuff, because I just don't want do unit tests right now :p
print get_video_thumbnail("http://www.youtube.com/watch?v=5g8ykQLYnX0", "default")
print get_video_thumbnail("http://youtu.be/IAooXLAPoBQ")
print get_video_thumbnail("http://www.youtube.com/watch?v=oavMtUWDBTM&embed=argument_useless&at=42")
print get_video_thumbnail("http://youtu.be/IAooXLAPoBQ", "1")
print get_video_thumbnail("http://www.dailymotion.com/video/xw6i2l_insalan-8-teaser_videogames?search_algo=2#.UVgyPhwtGK-")
print get_video_thumbnail("http://www.dailymotion.com/video/xrcz2c_django-unchained-trailer-bande-annonce-vo-hd_shortfilms?search_algo=2#.UVgzsxwtGK8")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment