Last active
December 15, 2015 15:19
-
-
Save mlorant/5280543 to your computer and use it in GitHub Desktop.
Just a little function to get thumbnail of video on Youtube or Dailymotion, based on the watch URL. Works with every youtube links, thanks to a great regex, found on stackoverflow, again. Useful when you want to do video list, without displaying every video embed on the same page.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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