Skip to content

Instantly share code, notes, and snippets.

@silentsokolov
Last active November 9, 2023 22:16
Show Gist options
  • Save silentsokolov/f5981f314bc006c82a41 to your computer and use it in GitHub Desktop.
Save silentsokolov/f5981f314bc006c82a41 to your computer and use it in GitHub Desktop.
Python: get youtube id
# Get youtube id
#http://youtu.be/5Y6HSHwhVlY
#http://www.youtube.com/embed/5Y6HSHwhVlY?rel=0
#http://www.youtube.com/watch?v=ZFqlHhCNBOI
regex = re.compile(r'(https?://)?(www\.)?(youtube|youtu|youtube-nocookie)\.(com|be)/(watch\?v=|embed/|v/|.+\?v=)?(?P<id>[A-Za-z0-9\-=_]{11})')
match = regex.match(self.youtube_url)
if not match:
print('no match')
print(match.group('id'))
# Online Test: https://pythex.org/?regex=(https%3F%3A%2F%2F)%3F(www%5C.)%3F(youtube%7Cyoutu%7Cyoutube-nocookie)%5C.(com%7Cbe)%2F(watch%5C%3Fv%3D%7Cembed%2F%7Cv%2F%7C.%2B%5C%3Fv%3D)%3F(%3FP%3Cid%3E%5BA-Za-z0-9%5C-%3D_%5D%7B11%7D)&test_string=http%3A%2F%2Fyoutu.be%2F5Y6HSHwhVlY%0Ahttp%3A%2F%2Fwww.youtube.com%2Fembed%2F5Y6HSHwhVlY%3Frel%3D0%0Ahttp%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DZFqlHhCNBOI&ignorecase=0&multiline=0&dotall=0&verbose=0
@ivansaul
Copy link

Thank you @silentsokolov, please check the url below, the regexp does not work for:

https://www.youtube.com/watch?time_continue=9&v=n0g-Y0oo5Qs&feature=emb_logo

I use this great package pytube, works with these urls.

url1='http://youtu.be/SA2iWivDJiE'
url2='http://www.youtube.com/watch?v=_oPAwA_Udwc&feature=feedu'
url3='http://www.youtube.com/embed/SA2iWivDJiE'
url4='http://www.youtube.com/v/SA2iWivDJiE?version=3&amp;hl=en_US'
url5='https://www.youtube.com/watch?v=rTHlyTphWP0&index=6&list=PLjeDyYvG6-40qawYNR4juzvSOg-ezZ2a6'
url6='youtube.com/watch?v=_lOT2p_FCvA'
url7='youtu.be/watch?v=_lOT2p_FCvA'
url8='https://www.youtube.com/watch?time_continue=9&v=n0g-Y0oo5Qs&feature=emb_logo'

check:

https://gist.github.com/ivansaul/ac2794ecbddec6c54f1c2e62cccfc175

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment