Created
July 2, 2014 08:09
-
-
Save mihneasim/14d1998883c3fb48ae78 to your computer and use it in GitHub Desktop.
Youtube downloader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" Simple youtube downloader """ | |
import re | |
import sys | |
import requests | |
import urllib | |
def youtube_info(youtube_id): | |
""" Raises ValueError when video is not streamable - e.g. VEVO video """ | |
info_url = 'http://www.youtube.com/get_video_info?video_id={0}' | |
resp = requests.get(info_url.format(youtube_id)) | |
pairs = resp.content.split('&') | |
mappings = dict((urllib.unquote(x.split('=')[0]), | |
urllib.unquote(x.split('=')[1])) for x in pairs) | |
if 'errorcode' in mappings: | |
raise ValueError("This YouTube video is not available for embedding") | |
if 'title' in mappings: | |
mappings['title'] = urllib.unquote_plus(mappings['title']) | |
return mappings | |
if __name__ == '__main__': | |
pat = re.compile(r'(?:https?:\/{2})?(?:w{3}\.)?youtu(?:be)?\.(?:com|be)(?:\/watch\?v=|\/)([^\s&]+)') | |
video_id = pat.match(sys.argv[1]).groups()[0] | |
mappings = youtube_info(video_id) | |
juice = mappings['url_encoded_fmt_stream_map'] | |
pairs = juice.split('&') | |
versions = [z for z in pairs if z.startswith('url=')] | |
temporary_url = urllib.unquote(versions[0][4:]) | |
resp = requests.get(temporary_url) | |
fp = open("%s.mp4" % mappings['title'], 'wb') | |
fp.write(resp.content) | |
fp.close() | |
print "Wrote %s.mp4" % mappings['title'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment