Skip to content

Instantly share code, notes, and snippets.

@rcscott
Created September 4, 2014 02:37
Show Gist options
  • Select an option

  • Save rcscott/b7bce6783e2f7820b67e to your computer and use it in GitHub Desktop.

Select an option

Save rcscott/b7bce6783e2f7820b67e to your computer and use it in GitHub Desktop.
###
# Parse video ID from URL
# Works for YouTube and Vimeo URLs, see test URLs below
#
# Returns a list including the parsed ID and the content provider (youtube or vimeo)
# e.g. ['id12345', 'youtube']
# If no match is found, function assumes parameter is a YouTube ID
#
# @author: rcscott
#
# Adapted from https://gist.github.com/takien/4077195 (JS implementation)
###
def parse_video_url_for_id(url):
# Try parsing for Vimeo video ID
if 'vimeo' in url:
isolate_vimeo_id = re.compile(r'vimeo.com/(?P<id>\d+)')
return [isolate_vimeo_id.search(url).group('id'), 'vimeo']
# Try parsing for YouTube video ID
video_id = url
split_before_id = re.compile(r'vi/|v=|/v/|youtu.be/|/embed/')
split_on_id = re.compile(r'[^0-9a-z_]', re.IGNORECASE)
try:
url = re.sub(r'>|<', '', video_id)
url = split_before_id.split(url)
if len(url) > 1:
video_id = split_on_id.split(url[1])[0]
return [video_id, 'youtube']
except:
return None
# Tested parameters
# BGL22PTIOAM - returns ['BGL22PTIOAM', 'youtube']
# http://youtube.googleapis.com/v/4e_kz79tjb8?version=3
# https://www.youtube.com/watch?feature=g-vrec&v=Y1xs_xPb46M
# http://www.youtube.com/watch?feature=player_embedded&v=Ab25nviakcw#
# http://youtu.be/Ab25nviakcw
# http://www.youtube.com/watch?v=Ab25nviakcw
# <iframe width="420" height="315" src="http://www.youtube.com/embed/Ab25nviakcw" frameborder="0" allowfullscreen></iframe>
# <object width="420" height="315"><param name="movie" value="http://www.youtube-nocookie.com/v/Ab25nviakcw?version=3&amp;hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube-nocookie.com/v/Ab25nviakcw?version=3&amp;hl=en_US" type="application/x-shockwave-flash" width="420" height="315" allowscriptaccess="always" allowfullscreen="true"></embed></object>
# http://i1.ytimg.com/vi/Ab25nviakcw/default.jpg
# https://www.youtube.com/watch?v=BGL22PTIOAM&feature=g-all-xit
# http://vimeo.com/88737187
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment