Downloading Youtube Videos using Python (One-liner)

If you just want to get or look into the code, here it is –

gist: 398604 – GitHub


I’ll walk through the code to explain how it works.

We need urllib and urlparse python modules so we import them –

from urllib import urlopen, unquote; from urlparse import parse_qs, urlparse;

youtube_watchurl is a self explanatory, we store the Youtube Watch URL here –


We need the v parameter value from the above Youtube Watch URL (Example: v=NeSuirvA6UE )

urlparse(youtube_watchurl).query returns the query part of the above URL i.e., “v=NeSuirvA6UE&playnext_from=TL&videos=MS3Hq4oBj08”. We need the value of ‘v’ parameter from this query string. parse_qs() function returns parameter name and value in dictionary format. parse_qs(…)[‘v’][0] returns the value of ‘v’ parameter.

video_id = parse_qs(urlparse(youtube_watchurl).query)['v'][0];

The below GET request will retrieve all video response like video title, description, tag, view count, rating etc and most importantly it also includes token string.

Just try

curl ""

to see the response from youtube. We need to parse the token string from the above response.

urlopen('' + video_id).read().decode('utf-8')

Similarly, as we have retrieve ‘v’ parameter value we retrieve the ‘token’ parameter value using below piece of code.

parse_qs(unquote(urlopen('' + video_id).read().decode('utf-8')))['token'][0])

example token value:


Now we have video id and token string, let’s put these value into the direct url to download the video. The format of the Direct URL:

Example Direct URL:

The above URL redirected me to below URL
The Direct URL may not work for more time after generating the token.

And that’s it we use the above direct link to download and write it to a file

open(video_id+'.mp4', 'wb').write(urlopen(""%(video_id, parse_qs(unquote(urlopen('' + video_id).read().decode('utf-8')))['token'][0])).read())

Here is the complete code:

gist: 398604 – GitHub

Inspired from Downloading YouTube Videos with a Perl One-Liner –


Stackoverflow:   (Coded in Python 3)

Posted on May 12, 2010
Written byAbhinay Omkar