Skip to content

Instantly share code, notes, and snippets.

@gileno
Created September 21, 2018 12:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gileno/8387191cb6123657603da08625bdfa59 to your computer and use it in GitHub Desktop.
Save gileno/8387191cb6123657603da08625bdfa59 to your computer and use it in GitHub Desktop.
from urllib.parse import urlparse, parse_qs
def video_id(value):
"""Video ID from youtube, vimeo and facebook links
>>> video_id('http://youtu.be/SA2iWivDJiE')
'SA2iWivDJiE'
>>> video_id('http://www.youtube.com/watch?v=_oPAwA_Udwc&feature=feedu')
'_oPAwA_Udwc'
>>> video_id('http://www.youtube.com/embed/SA2iWivDJiE')
'SA2iWivDJiE'
>>> video_id('http://www.youtube.com/v/SA2iWivDJiE?version=3&hl=en_US')
'SA2iWivDJiE'
>>> video_id('http://vimeo.com/999999')
'999999'
>>> video_id('http://www.vimeo.com/999999')
'999999'
>>> video_id('http://player.vimeo.com/video/999999')
'999999'
>>> video_id('https://facebook.com/pagina/videos/9999999999999999/')
'9999999999999999'
>>> video_id('https://web.facebook.com/pagina/videos/9999999999999999/')
'9999999999999999'
>>> video_id('https://www.facebook.com/pagina/videos/9999999999999999/')
'9999999999999999'
"""
result = urlparse(value)
if result.hostname == 'youtu.be':
return result.path[1:]
if result.hostname in ('www.youtube.com', 'youtube.com'):
if result.path == '/watch':
p = parse_qs(result.query)
return p['v'][0]
if result.path[:7] == '/embed/':
return result.path.split('/')[2]
if result.path[:3] == '/v/':
return result.path.split('/')[2]
if result.hostname in ('vimeo.com', 'www.vimeo.com'):
return result.path.split('/')[1]
elif result.hostname == 'player.vimeo.com':
return result.path.split('/')[2]
if result.hostname in ('web.facebook.com', 'facebook.com', 'www.facebook.com'):
return result.path.split('/')[3]
return None
if __name__ == '__main__':
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment