Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I extract video ID from YouTube's link in Python?

Tags:

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?

like image 738
decarbo Avatar asked Dec 04 '10 23:12

decarbo


People also ask

How do I get the YouTube video ID from a URL?

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 .


2 Answers

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 
like image 179
Mikhail Kashkin Avatar answered Oct 11 '22 04:10

Mikhail Kashkin


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] 
like image 22
robert Avatar answered Oct 11 '22 03:10

robert