I know this can be easily done using PHP's parse_url
and parse_str
functions:
$subject = "http://www.youtube.com/watch?v=z_AbfPXTKms&NR=1"; $url = parse_url($subject); parse_str($url['query'], $query); var_dump($query);
But how to achieve this using Python? I can do urlparse
but what next?
The video ID will be located in the URL of the video page, right after the v= URL parameter. In this case, the URL of the video is: https://www.youtube.com/watch?v=aqz-KE-bpKQ. Therefore, the ID of the video is aqz-KE-bpKQ .
I've created youtube id parser without regexp:
import urlparse def video_id(value): """ Examples: - http://youtu.be/SA2iWivDJiE - http://www.youtube.com/watch?v=_oPAwA_Udwc&feature=feedu - http://www.youtube.com/embed/SA2iWivDJiE - http://www.youtube.com/v/SA2iWivDJiE?version=3&hl=en_US """ query = urlparse.urlparse(value) if query.hostname == 'youtu.be': return query.path[1:] if query.hostname in ('www.youtube.com', 'youtube.com'): if query.path == '/watch': p = urlparse.parse_qs(query.query) return p['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
Python has a library for parsing URLs.
import urlparse url_data = urlparse.urlparse("http://www.youtube.com/watch?v=z_AbfPXTKms&NR=1") query = urlparse.parse_qs(url_data.query) video = query["v"][0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With