1+ #!/usr/bin/env python3
2+
3+
4+ """
5+ A script to download multiple videos from youtube.
6+ """
7+
8+ import sys
9+ import urllib .request
10+ from urllib .request import urlopen , FancyURLopener
11+ from urllib .parse import urlparse , parse_qs , unquote
12+
13+ class UndercoverURLopener (FancyURLopener ):
14+ version = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_8; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.9 Safari/533.2"
15+
16+ urllib .request ._urlopener = UndercoverURLopener ()
17+
18+ def youtube_download (video_url ):
19+ video_id = parse_qs (urlparse (video_url ).query )['v' ][0 ]
20+
21+ url_data = urlopen ('http://www.youtube.com/get_video_info?&video_id=' + video_id ).read ()
22+ url_info = parse_qs (unquote (url_data .decode ('utf-8' )))
23+ token_value = url_info ['token' ][0 ]
24+
25+ download_url = "http://www.youtube.com/get_video?video_id={0}&t={1}&fmt=18" .format (
26+ video_id , token_value )
27+
28+ video_title = url_info ['title' ][0 ] if 'title' in url_info else ''
29+ # Unicode filenames are more trouble than they're worth
30+ filename = video_title .encode ('ascii' , 'ignore' ).decode ('ascii' ).replace ("/" , "-" ) + '.mp4'
31+
32+ print ("\t Downloading '{}' to '{}'..." .format (video_title , filename ))
33+
34+ try :
35+ download = urlopen (download_url ).read ()
36+ f = open (filename , 'wb' )
37+ f .write (download )
38+ f .close ()
39+ except Exception as e :
40+ print ("\t Downlad failed! {}" .format (str (e )))
41+ print ("\t Skipping..." )
42+ else :
43+ print ("\t Done." )
44+
45+ def main ():
46+ print ("\n --------------------------" )
47+ print (" Youtube Video Downloader" )
48+ print ("--------------------------\n " )
49+
50+ try :
51+ video_urls = sys .argv [1 :]
52+ except :
53+ video_urls = input ('Enter (space-separated) video URLs: ' )
54+
55+ for u in video_urls :
56+ youtube_download (u )
57+ print ("\n Done." )
58+
59+ if __name__ == '__main__' :
60+ main ()
0 commit comments