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,expire,ip,ipbits,itag,algorithm,burst,factor,oc:U0dWSFZUVl9FSkNNNl9OTlpB&fexp=903801,903206&algorithm=throttle-factor&itag=18&ipbits=0&burst=40&sver=3&expire=1273698000&key=yt1&signature=5F8E3C3EABC00FE77AB5699811B13957CA95CFFD.14D37482C6E22D91D08770C6630EE3BE3BF9732D&factor=1.25&id=35e4ae8abbc0e941
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)

This entry was posted in Uncategorized. Bookmark the permalink.

One Response to Downloading Youtube Videos using Python (One-liner)

  1. Pingback: » Blog Archive » Hang Lung’s Chan Sees No Bubble in China Property Market: Video

Comments are closed.