Search code examples
pythonregexparsingurl-parsing

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


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?


Solution

  • 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]