youtube video id
extract_video_id.py
from urllib.parse import urlparse, parse_qs
urltext = 'https://www.youtube.com/watch?v=T99Ng11MPdY'
def extract_video_id(url):
query = urlparse(url)
if query.hostname == 'youtu.be': return query.path[1:]
if query.hostname in {'www.youtube.com', 'youtube.com'}:
if query.path == '/watch': return parse_qs(query.query)['v'][0]
if query.path[:7] == '/embed/': return query.path.split('/')[2]
if query.path[:3] == '/v/': return query.path.split('/')[2]
# fail?
return None
if __name__ == "__main__":
args = [urltext]
video_id = ''
for url in args:
video_id = (extract_video_id(url))
print(video_id)
Cf.
Extracting video id from YouTube URL and extractiong subtitles to subtitle.txt