Skip to content

Instantly share code, notes, and snippets.

@ivansaul
Last active December 30, 2022 12:55
Show Gist options
  • Save ivansaul/ac2794ecbddec6c54f1c2e62cccfc175 to your computer and use it in GitHub Desktop.
Save ivansaul/ac2794ecbddec6c54f1c2e62cccfc175 to your computer and use it in GitHub Desktop.
Python: Get youtube id | Extract Video id from a Youtube url
#pip install pytube
#Examples
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&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'
urls=[url1,url2,url3,url4,url5,url6,url7,url8]
#Get youtube id
from pytube import extract
for url in urls:
id=extract.video_id(url)
print(id)
# Output
'''
SA2iWivDJiE
_oPAwA_Udwc
SA2iWivDJiE
SA2iWivDJiE
rTHlyTphWP0
_lOT2p_FCvA
_lOT2p_FCvA
n0g-Y0oo5Qs
'''
@mendel5
Copy link

mendel5 commented May 12, 2021

Very nice, thank you!

@emrecpp
Copy link

emrecpp commented Nov 5, 2022

If you don't want to use pytube library;

def parseYoutubeURL(self, url:str)->str:
   data = re.findall(r"(?:v=|\/)([0-9A-Za-z_-]{11}).*", url)
   if data:
       return data[0]
   return ""

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