Welcome, guest | Sign In | My Account | Store | Cart

This tool simple provides downloading videos from youtube with support for STDIN (PIPE) for tools like umph or youParse.

UPDATE INFO: Youtube has recently changed their service so this tool may not work on some other links. Will update very soon. (edited: 29-12-2012)

Python, 340 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
#!/usr/bin/python3

# Name: tubeNick.py
# Version: 1.6
# Author: pantuts
# Description: Download videos from youtube.
# Use python3 and later.
# Agreement: You can use, modify, or redistribute this tool under 
# the terms of GNU General Public License (GPLv3). This tool is for educational purposes only.
# Any damage you make will not affect the author.
# Send bugs to above email.
# Usage: python3 tubeNick.py youtubeURLhere
# Download: https://sourceforge.net/projects/tubenickdownloa/

import re
import urllib.request
import urllib.error
import sys
import time

COLON = '%253A'
BACKSLASH = '%252F'
QMARK = '%253F'
EQUALS = '%253D'
AMPERSAND = '%2526'
PERCENT = '%2525'

MATCHED_LINK = []
SIGNATURE = []
COMPLETE_LINK = []
VIDEO_TYPE = []
VIDEO_RES = []
FINAL_LINK = []

sTUBE = ''
final_title = ''
final_url = ''
url = ''
final_f_format = 0
arg_queryf = ''
arg_format = ''
arg_f_format = []

########################################################################

def main():

    global url
    global arg_format
    global arg_queryf
    
    if len(sys.argv) < 2 or len(sys.argv) > 4: return usage()
    elif len(sys.argv) == 2:
        if sys.argv[-1] == '-h': return usage()
        else:
            if sys.argv[-1] == '-': url = list(sys.stdin.readlines())
            else: url = sys.argv[-1]
    elif len(sys.argv) == 3:
        for args in sys.argv:
            if '-h' in args or '-f' in args: print('\nCommand ERROR...'); exit(1)
        if sys.argv[1] == '-q': sys.argv[1] = '-q'; arg_queryf = sys.argv[1]
        else: return usage()
        if sys.argv[-1] == '-': url = list(sys.stdin.readlines())
        else: url = sys.argv[-1]
    elif len(sys.argv) == 4:
        for args in sys.argv:
            if '-h' in args or '-q' in args: print('\nCommand ERROR...'); exit(1)
        if sys.argv[1] == '-f': sys.argv[1] = '-f';
        else: return usage()
        arg_format = sys.argv[2]
        if sys.argv[-1] == '-': url = list(sys.stdin.readlines())
        else: url = sys.argv[-1]
    else: return usage()
   
    if sys.argv[-1] == '-':
        
        i = 0
        while i < len(url):
            check_url(url[i].split('\\')[0])
            i = i + 1
    else:
        check_url(url)
    
########################################################################

def usage():

    print('\nUSAGE: python3 tubeNick.py -q [-f format] [URL or [-] STDIN]')
    print('Optional arguments:')
    print('\t-q \t\tQuery video formats. Use of -f will be invalid.')
    print('\t-f format\tSupply queried format. Highest video if blank.')
    print('\t-h \t\tPrint this.')
    print()

########################################################################

def check_url(url):
    
    global final_url
    
    tmp_url = 'http://www.youtube.com/get_video_info?video_id='
    #invalid = '~`!@#$%^&*()_=+{[}]|\\:;"\'<,>.?/'
    tmp_id = ''
    final_id = ''
    eq = 0
    last_id = 0
    
    split_url = url.split('/')
    tmp_id = split_url[-1]
    
    if 'v' not in url: print('[-] URLError: Invalid link.'); exit(1)
    if len(url) < 20: print('[-] URLError: Invalid link.'); exit(1)
    if 'youtube.com' not in url and url != '-': print('[-] URLError: Youtube URLs only.'); exit(1)
    
    if 'watch?v=' in tmp_id:
        eq = tmp_id.index('=') + 1
        if '&' in tmp_id:
            tmp_split = tmp_id.split('&')[0]
            final_id = tmp_split[eq:]
        else: final_id = tmp_id[eq:]
    
    # the video id for requesting get_video_info
    final_url = tmp_url + final_id
    
    if final_url:
        con = 'Connecting...\n'
        i = 0
        while i < len(con):
            sys.stdout.write(con[i])
            sys.stdout.flush()
            time.sleep(0.01)
            i = i + 1
            
        connection(final_url)

########################################################################

def connection(final_url):

    global sTUBE
    
    try:
        req = urllib.request.Request(final_url)
        req.add_header('User-Agent', 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:16.0) Gecko/20100101 Firefox/16.0')
        yTUBE = urllib.request.urlopen(req)
        sTUBE = str(yTUBE.read())
        
    except urllib.request.URLError as e: print(e.reason); exit(1)
    
    if sTUBE:
        rep_page(sTUBE)

########################################################################

def rep_page(sTUBE):

    REP_STR = [COLON, BACKSLASH, QMARK, EQUALS, AMPERSAND, PERCENT]
    if REP_STR[0] in sTUBE:
        sTUBE = sTUBE.replace('%253A', ':')
    if REP_STR[1] in sTUBE:
        sTUBE = sTUBE.replace('%252F', '/')
    if REP_STR[2] in sTUBE:
        sTUBE = sTUBE.replace('%253F', '?')
    if REP_STR[3] in sTUBE:
        sTUBE = sTUBE.replace('%253D', '=')
    if REP_STR[4] in sTUBE:
        sTUBE = sTUBE.replace('%2526', '&')
    if REP_STR[5] in sTUBE:
        sTUBE = sTUBE.replace('%2525', '%')
    
    crawl_youtube(sTUBE)
    
########################################################################

def crawl_youtube(sTUBE):

    global VIDEO_TITLE
    global MATCHED_LINK
    global SIGNATURE
    global COMPLETE_LINK
    global VIDEO_TYPE
    global VIDEO_RES
    global final_title
    global final_f_format
    global arg_f_format
    
    # get title
    vid_title = re.search(r'title=\w.+', sTUBE)
    if vid_title:
        the_title = vid_title.group()
        if '&' in the_title:
            tmp_title = the_title.index('&')
        else: tmp_title = len(the_title) - 1
        f_title = the_title[6:tmp_title]
        final_title = f_title.replace('+', ' ')
        for per_num in ['%21','%22','%23','%24','%25','%26','%27','%28','%29',\
        '%2D','%5F','%3D','%2B','%5B','%7B','%7D','%5D','%7C','%5C',\
        '%3A','%3B','%2C','%3C','%3E','%2E','%3F','%2F']:
            if per_num in final_title:
                final_title = final_title.replace(per_num, '')
    else: print('[-] ERROR: Can\'t find video title. Title set to default.'); final_title = 'DownloadYTube'
    
    # get links
    match = re.findall(r'http://\w.+?cp.+?video.+?quality.+?3D\w.+?%', sTUBE)
    if match:
        for mat in match:
        
            MATCHED_LINK.append(mat)
            
            # get signature
            find_sig = re.search(r'sig+\S.+quality', mat)
            if find_sig:
                c_sig = find_sig.group()
                final_sig = c_sig[6:-10]
                SIGNATURE.append(final_sig)
                #print(final_sig)
                
            # for link / get last characters [id]
            if 'id=' in mat:
                y_index = mat.index('id=')
                id_last = y_index + 19
                li = mat[:id_last]
                COMPLETE_LINK.append(li)
                
            # get video type
            if 'video/' in mat:
                vid_start = mat.index('video/')
                vid_end = vid_start + 11
                vid_type = mat[vid_start:vid_end]
                for vid_cod in ['flv', 'webm', 'mp4', '3gp']:
                    if vid_cod in vid_type:
                        VIDEO_TYPE.append(vid_cod)
                        
    else: print('[-] URLError'); exit(1)
                
    # get formats/resolution
    fmt = re.search(r'fmt_list=\S.+?\&', sTUBE)
    if fmt:
        frmt = fmt.group().split('%2F')
        for v_format in frmt:
            if 'x' in v_format:
                VIDEO_RES.append(v_format)
    else: print('Can\'t find video formats. '); exit(1)
    
    # append and combine video type and resolution
    j = 0
    while j < len(COMPLETE_LINK):
        arg_f_format.append(VIDEO_TYPE[j] + '_' + VIDEO_RES[j])
        j = j + 1
    
    # if argument is [ -q ]
    if arg_queryf:
        i = 0
        print(final_title)
        while i < len(COMPLETE_LINK):
            print('[+] ' + VIDEO_TYPE[i] + '_' + VIDEO_RES[i])
            time.sleep(0.04)
            i = i + 1
        flush()
        
    else:
            
        # if argument is [ -f ] and the default format
        if arg_format is not None and arg_format in arg_f_format:
            final_f_format = arg_f_format.index(arg_format)
        elif arg_format not in arg_f_format and len(sys.argv) != 2:
            print('' + arg_format + ' not in video formats. Setting to default format: ', arg_f_format[0])
            final_f_format = 0
        else:
            final_f_format = 0
        
        final_download_link()

########################################################################

def final_download_link():

    global FINAL_LINK
    
    i = 0
    while i < len(COMPLETE_LINK):
        FINAL_LINK.append(COMPLETE_LINK[i] + '&signature=' + SIGNATURE[i])
        i = i + 1
        
    download()
    
########################################################################

def download():

    req = urllib.request.Request(FINAL_LINK[final_f_format])
    req.add_header('User-Agent', 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:16.0) Gecko/20100101 Firefox/16.0')
    try:
        tmp_req = urllib.request.urlopen(req)
        tmp_size = tmp_req.getheader('Content-Length')
        size = int(tmp_size)
        
        print('Downloading...')
        
        # for reporthook in urlretrieve, 3 arguments needed
        def download_progress(counter, bsize, size):
            prog_percent = (counter * bsize * 100) / size
            sys.stdout.write('\r' + final_title.replace(' ', '') + '.' + VIDEO_TYPE[final_f_format] + \
                    ' .......................... %2.f%%' % int(prog_percent))
            sys.stdout.flush()

        urllib.request.urlretrieve(FINAL_LINK[final_f_format], (final_title.replace(' ', '') + \
                    '.' + VIDEO_TYPE[final_f_format]), reporthook=download_progress)
        print('\nDone.')
        flush()
        
    except urllib.error.HTTPError as e: print('Error downloading : ' + e.reason); exit(1)
        
########################################################################

def flush():

    del MATCHED_LINK[:]
    del SIGNATURE[:]
    del COMPLETE_LINK[:]
    del VIDEO_TYPE[:]
    del VIDEO_RES[:]
    del FINAL_LINK[:]

    sTUBE = ''
    final_title = ''
    final_url = ''
    url = ''
    final_f_format = 0
    arg_queryf = ''
    arg_format = ''
    del arg_f_format[:]

########################################################################

if __name__ =='__main__':
    try:
        main()
    except KeyboardInterrupt:
        print('\nExiting.')

Sample usage:

python3 tubeNick.py url

'This will download videos as default and video format will be the highest video resolution.'

python3 tubeNick.py -q url

'Query available formats.'

python3 tubeNick.py -f webm_1920x720 url

'Download by -f format.'

[ERROR]

python3 tubeNick.py -q -f webm_1920x720 url

'Will raise error.'

[PIPING]

python3 youParse.py playlist | python3 tubeNick.py -

'Download all videos from youParse.py extracted links.'

python3 youParse.py playlist | python3 tubeNick.py -q -

python3 youParse.py playlist | python3 tubeNick.py -f webm_1920x720 -

3 comments

Dan Zemke 11 years, 4 months ago  # | flag

I just did a clean install of Windows 8 and Python 3.3, downloaded your code, and tried it. Simple UI (including progress bar), clear code, and best of all (of course) - it works. Thanks!

p@ntut$ (author) 11 years, 4 months ago  # | flag

Hey thanks Dan! I'll update it soon too. Need to change some few lines of codes regarding the support for stdin and its format. Thanks again!

george cooke 11 years ago  # | flag

Hey thanks for this but it has stopped working, i think youtube has changed the order in something in the url_encoded_fmt_stream_map so with your script on linux, windows and cygwin python 3's i get forbidden from youtube (an incorrect request).

However I don't know python and i really needed a script right now to download videos overnight (poor internet in daytime on vacation) so i stayed up all night getting one working in Perl but it's quite dirty.

After all that; guess what i just found: youtube-dl (http://rg3.github.com/youtube-dl/) is a full featured cross-platform youtube ('and other sites') command-line downloader (apparently written in python) and has some good options, can update itself etc and it works as of today 25th March 2013. SO, maybe save you some time, unless you need other functionality. You can feed it an id or user page or a playlist page with start and end points and it will grab them all and it can do all the format stuff (i like --max-quality).

Created by p@ntut$ on Tue, 16 Oct 2012 (GPL3)
Python recipes (4591)
p@ntut$'s recipes (7)

Required Modules

  • (none specified)

Other Information and Tasks