Bruce
Bruce

Reputation: 35285

Parsing all possible YouTube urls

I am looking for all the features that a YouTube url can have?

http://www.youtube.com/watch?v=6FWUjJF1ai0&feature=related

So far I have seen feature=relmfu, related, fvst, fvwrel. Is there a list for this somewhere. Also, my ultimate aim is to extract the video id (6FWUjJF1ai) from all possible youtube urls. How can I do that? It seems to be difficult. Is there anyone who has already done that?

Upvotes: 2

Views: 1998

Answers (4)

vinyll
vinyll

Reputation: 11419

You may rather want to consider a wider spectrum of url parser as suggested on this Gist.

It will parse more than what urlparse can do.

Upvotes: 0

Rodrigo Borges
Rodrigo Borges

Reputation: 126

From the following answer https://stackoverflow.com/a/43490746/8534966, I ran 55 different test cases and it was able to get 51 matches. See my tests.

So I wrote some if else code to fix it:

# Get YouTube video ID
if "watch%3Fv%3D" in youtube_url:
    # e.g.: https://www.youtube.com/attribution_link?a=8g8kPrPIi-ecwIsS&u=/watch%3Fv%3DyZv2daTWRZU%26feature%3Dem-uploademail
    search_pattern = re.search("watch%3Fv%3D(.*?)%", youtube_url)
    if search_pattern:
        youtube_id = search_pattern.group(1)
elif "watch?v%3D" in youtube_url:
    # e.g.: http://www.youtube.com/attribution_link?a=JdfC0C9V6ZI&u=%2Fwatch%3Fv%3DEhxJLojIE_o%26feature%3Dshare
    search_pattern = re.search("v%3D(.*?)&format", youtube_url)
    if search_pattern:
        youtube_id = search_pattern.group(1)
elif "/e/" in youtube_url:
    # e.g.: http://www.youtube.com/e/dQw4w9WgXcQ
    youtube_url += " "
    search_pattern = re.search("/e/(.*?) ", youtube_url)
    if search_pattern:
        youtube_id = search_pattern.group(1)
else:
    # All else.
    search_pattern = re.search("(?:[?&]vi?=|\/embed\/|\/\d\d?\/|\/vi?\/|https?:\/\/(?:www\.)?youtu\.be\/)([^&\n?#]+)",
                               youtube_url)
    if search_pattern:
        youtube_id = search_pattern.group(1)

Upvotes: 0

Arnab Ghosal
Arnab Ghosal

Reputation: 521

wrote the code for your assistance....the credit of solving is purely Frank's though.

import urlparse as ups
m = ups.urlparse('http://www.youtube.com/watch?v=6FWUjJF1ai0&feature=related')
print ups.parse_qs(m.query)['v']

Upvotes: 3

Frank
Frank

Reputation: 76

You can use urlparse to get the query string from your url, then you can use parse_qs to get the video id from the query string.

Upvotes: 6

Related Questions