11 from .common import InfoExtractor, SearchInfoExtractor
12 from .subtitles import SubtitlesInfoExtractor
13 from ..jsinterp import JSInterpreter
14 from ..swfinterp import SWFInterpreter
19 compat_urllib_request,
26 get_element_by_attribute,
37 class YoutubeBaseInfoExtractor(InfoExtractor):
38 """Provide base functions for Youtube extractors"""
39 _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
40 _LANG_URL = r'https://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
41 _AGE_URL = 'https://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
42 _NETRC_MACHINE = 'youtube'
43 # If True it will raise an error if no login info is provided
44 _LOGIN_REQUIRED = False
46 def _set_language(self):
47 return bool(self._download_webpage(
49 note=u'Setting language', errnote='unable to set language',
53 (username, password) = self._get_login_info()
54 # No authentication to be performed
56 if self._LOGIN_REQUIRED:
57 raise ExtractorError(u'No login info available, needed for using %s.' % self.IE_NAME, expected=True)
60 login_page = self._download_webpage(
61 self._LOGIN_URL, None,
62 note=u'Downloading login page',
63 errnote=u'unable to fetch login page', fatal=False)
64 if login_page is False:
67 galx = self._search_regex(r'(?s)<input.+?name="GALX".+?value="(.+?)"',
68 login_page, u'Login GALX parameter')
72 u'continue': u'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
76 u'PersistentCookie': u'yes',
78 u'bgresponse': u'js_disabled',
79 u'checkConnection': u'',
80 u'checkedDomains': u'youtube',
85 u'signIn': u'Sign in',
87 u'service': u'youtube',
91 # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
93 login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k,v in login_form_strs.items())
94 login_data = compat_urllib_parse.urlencode(login_form).encode('ascii')
96 req = compat_urllib_request.Request(self._LOGIN_URL, login_data)
97 login_results = self._download_webpage(
99 note=u'Logging in', errnote=u'unable to log in', fatal=False)
100 if login_results is False:
102 if re.search(r'(?i)<form[^>]* id="gaia_loginform"', login_results) is not None:
103 self._downloader.report_warning(u'unable to log in: bad username or password')
107 def _confirm_age(self):
110 'action_confirm': 'Confirm',
112 req = compat_urllib_request.Request(self._AGE_URL,
113 compat_urllib_parse.urlencode(age_form).encode('ascii'))
115 self._download_webpage(
117 note=u'Confirming age', errnote=u'Unable to confirm age')
120 def _real_initialize(self):
121 if self._downloader is None:
123 if not self._set_language():
125 if not self._login():
130 class YoutubeIE(YoutubeBaseInfoExtractor, SubtitlesInfoExtractor):
131 IE_DESC = u'YouTube.com'
132 _VALID_URL = r"""(?x)^
134 (?:https?://|//)? # http(s):// or protocol-independent URL (optional)
135 (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/|
136 (?:www\.)?deturl\.com/www\.youtube\.com/|
137 (?:www\.)?pwnyoutube\.com/|
138 (?:www\.)?yourepeat\.com/|
139 tube\.majestyc\.net/|
140 youtube\.googleapis\.com/) # the various hostnames, with wildcard subdomains
141 (?:.*?\#/)? # handle anchor (#/) redirect urls
142 (?: # the various things that can precede the ID:
143 (?:(?:v|embed|e)/) # v/ or embed/ or e/
144 |(?: # or the v= param in all its forms
145 (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
146 (?:\?|\#!?) # the params delimiter ? or # or #!
147 (?:.*?&)? # any other preceding param (like /?s=tuff&v=xxxx)
151 |youtu\.be/ # just youtu.be/xxxx
152 |https?://(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
154 )? # all until now is optional -> you can pass the naked ID
155 ([0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
156 (?(1).+)? # if we found the ID, everything can follow
158 _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
160 '5': {'ext': 'flv', 'width': 400, 'height': 240},
161 '6': {'ext': 'flv', 'width': 450, 'height': 270},
162 '13': {'ext': '3gp'},
163 '17': {'ext': '3gp', 'width': 176, 'height': 144},
164 '18': {'ext': 'mp4', 'width': 640, 'height': 360},
165 '22': {'ext': 'mp4', 'width': 1280, 'height': 720},
166 '34': {'ext': 'flv', 'width': 640, 'height': 360},
167 '35': {'ext': 'flv', 'width': 854, 'height': 480},
168 '36': {'ext': '3gp', 'width': 320, 'height': 240},
169 '37': {'ext': 'mp4', 'width': 1920, 'height': 1080},
170 '38': {'ext': 'mp4', 'width': 4096, 'height': 3072},
171 '43': {'ext': 'webm', 'width': 640, 'height': 360},
172 '44': {'ext': 'webm', 'width': 854, 'height': 480},
173 '45': {'ext': 'webm', 'width': 1280, 'height': 720},
174 '46': {'ext': 'webm', 'width': 1920, 'height': 1080},
178 '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'preference': -20},
179 '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'preference': -20},
180 '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'preference': -20},
181 '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'preference': -20},
182 '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'preference': -20},
183 '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'preference': -20},
184 '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'preference': -20},
186 # Apple HTTP Live Streaming
187 '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'preference': -10},
188 '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'preference': -10},
189 '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'preference': -10},
190 '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'preference': -10},
191 '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'preference': -10},
192 '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'preference': -10},
193 '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'preference': -10},
196 '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
197 '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
198 '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
199 '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
200 '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
201 '138': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
202 '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
203 '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
206 '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 48, 'preference': -50},
207 '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 128, 'preference': -50},
208 '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 256, 'preference': -50},
211 '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
212 '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
213 '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
214 '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
215 '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
216 '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
217 '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
218 '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
219 '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
220 '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
221 '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
222 '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
223 '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
224 '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
225 '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
228 '171': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'abr': 128, 'preference': -50},
229 '172': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'abr': 256, 'preference': -50},
232 '_rtmp': {'protocol': 'rtmp'},
238 u"url": u"http://www.youtube.com/watch?v=BaW_jenozKc",
239 u"file": u"BaW_jenozKc.mp4",
241 u"title": u"youtube-dl test video \"'/\\ä↭𝕐",
242 u"uploader": u"Philipp Hagemeister",
243 u"uploader_id": u"phihag",
244 u"upload_date": u"20121002",
245 u"description": u"test chars: \"'/\\ä↭𝕐\ntest URL: https://github.com/rg3/youtube-dl/issues/1892\n\nThis is a test video for youtube-dl.\n\nFor more information, contact phihag@phihag.de .",
246 u"categories": [u'Science & Technology'],
250 u"url": u"http://www.youtube.com/watch?v=UxxajLWwzqY",
251 u"file": u"UxxajLWwzqY.mp4",
252 u"note": u"Test generic use_cipher_signature video (#897)",
254 u"upload_date": u"20120506",
255 u"title": u"Icona Pop - I Love It (feat. Charli XCX) [OFFICIAL VIDEO]",
256 u"description": u"md5:fea86fda2d5a5784273df5c7cc994d9f",
257 u"uploader": u"Icona Pop",
258 u"uploader_id": u"IconaPop"
262 u"url": u"https://www.youtube.com/watch?v=07FYdnEawAQ",
263 u"file": u"07FYdnEawAQ.mp4",
264 u"note": u"Test VEVO video with age protection (#956)",
266 u"upload_date": u"20130703",
267 u"title": u"Justin Timberlake - Tunnel Vision (Explicit)",
268 u"description": u"md5:64249768eec3bc4276236606ea996373",
269 u"uploader": u"justintimberlakeVEVO",
270 u"uploader_id": u"justintimberlakeVEVO"
274 u"url": u"//www.YouTube.com/watch?v=yZIXLfi8CZQ",
275 u"file": u"yZIXLfi8CZQ.mp4",
276 u"note": u"Embed-only video (#1746)",
278 u"upload_date": u"20120608",
279 u"title": u"Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012",
280 u"description": u"md5:09b78bd971f1e3e289601dfba15ca4f7",
281 u"uploader": u"SET India",
282 u"uploader_id": u"setindia"
286 u"url": u"http://www.youtube.com/watch?v=a9LDPn-MO4I",
287 u"file": u"a9LDPn-MO4I.m4a",
288 u"note": u"256k DASH audio (format 141) via DASH manifest",
290 u"upload_date": "20121002",
291 u"uploader_id": "8KVIDEO",
292 u"description": "No description available.",
293 u"uploader": "8KVIDEO",
294 u"title": "UHDTV TEST 8K VIDEO.mp4"
297 u"youtube_include_dash_manifest": True,
301 # DASH manifest with encrypted signature
303 u'url': u'https://www.youtube.com/watch?v=IB3lcPjvWLA',
305 u'id': u'IB3lcPjvWLA',
307 u'title': u'Afrojack - The Spark ft. Spree Wilson',
308 u'description': u'md5:9717375db5a9a3992be4668bbf3bc0a8',
309 u'uploader': u'AfrojackVEVO',
310 u'uploader_id': u'AfrojackVEVO',
311 u'upload_date': u'20131011',
314 u'youtube_include_dash_manifest': True,
322 def suitable(cls, url):
323 """Receives a URL and returns True if suitable for this IE."""
324 if YoutubePlaylistIE.suitable(url): return False
325 return re.match(cls._VALID_URL, url) is not None
327 def __init__(self, *args, **kwargs):
328 super(YoutubeIE, self).__init__(*args, **kwargs)
329 self._player_cache = {}
331 def report_video_info_webpage_download(self, video_id):
332 """Report attempt to download video info webpage."""
333 self.to_screen(u'%s: Downloading video info webpage' % video_id)
335 def report_information_extraction(self, video_id):
336 """Report attempt to extract video information."""
337 self.to_screen(u'%s: Extracting video information' % video_id)
339 def report_unavailable_format(self, video_id, format):
340 """Report extracted video URL."""
341 self.to_screen(u'%s: Format %s not available' % (video_id, format))
343 def report_rtmp_download(self):
344 """Indicate the download will use the RTMP protocol."""
345 self.to_screen(u'RTMP download detected')
347 def _signature_cache_id(self, example_sig):
348 """ Return a string representation of a signature """
349 return u'.'.join(compat_str(len(part)) for part in example_sig.split('.'))
351 def _extract_signature_function(self, video_id, player_url, example_sig):
353 r'.*-(?P<id>[a-zA-Z0-9_-]+)(?:/watch_as3|/html5player)?\.(?P<ext>[a-z]+)$',
356 raise ExtractorError('Cannot identify player %r' % player_url)
357 player_type = id_m.group('ext')
358 player_id = id_m.group('id')
360 # Read from filesystem cache
361 func_id = '%s_%s_%s' % (
362 player_type, player_id, self._signature_cache_id(example_sig))
363 assert os.path.basename(func_id) == func_id
364 cache_dir = get_cachedir(self._downloader.params)
366 cache_enabled = cache_dir is not None
368 cache_fn = os.path.join(os.path.expanduser(cache_dir),
372 with io.open(cache_fn, 'r', encoding='utf-8') as cachef:
373 cache_spec = json.load(cachef)
374 return lambda s: u''.join(s[i] for i in cache_spec)
376 pass # No cache available
379 file_size = os.path.getsize(cache_fn)
380 except (OSError, IOError) as oe:
382 self._downloader.report_warning(
383 u'Cache %s failed (%s)' % (cache_fn, file_size))
385 if player_type == 'js':
386 code = self._download_webpage(
387 player_url, video_id,
388 note=u'Downloading %s player %s' % (player_type, player_id),
389 errnote=u'Download of %s failed' % player_url)
390 res = self._parse_sig_js(code)
391 elif player_type == 'swf':
392 urlh = self._request_webpage(
393 player_url, video_id,
394 note=u'Downloading %s player %s' % (player_type, player_id),
395 errnote=u'Download of %s failed' % player_url)
397 res = self._parse_sig_swf(code)
399 assert False, 'Invalid player type %r' % player_type
403 test_string = u''.join(map(compat_chr, range(len(example_sig))))
404 cache_res = res(test_string)
405 cache_spec = [ord(c) for c in cache_res]
407 os.makedirs(os.path.dirname(cache_fn))
408 except OSError as ose:
409 if ose.errno != errno.EEXIST:
411 write_json_file(cache_spec, cache_fn)
413 tb = traceback.format_exc()
414 self._downloader.report_warning(
415 u'Writing cache to %r failed: %s' % (cache_fn, tb))
419 def _print_sig_code(self, func, example_sig):
420 def gen_sig_code(idxs):
421 def _genslice(start, end, step):
422 starts = u'' if start == 0 else str(start)
423 ends = (u':%d' % (end+step)) if end + step >= 0 else u':'
424 steps = u'' if step == 1 else (u':%d' % step)
425 return u's[%s%s%s]' % (starts, ends, steps)
428 start = '(Never used)' # Quelch pyflakes warnings - start will be
429 # set as soon as step is set
430 for i, prev in zip(idxs[1:], idxs[:-1]):
434 yield _genslice(start, prev, step)
437 if i - prev in [-1, 1]:
442 yield u's[%d]' % prev
446 yield _genslice(start, i, step)
448 test_string = u''.join(map(compat_chr, range(len(example_sig))))
449 cache_res = func(test_string)
450 cache_spec = [ord(c) for c in cache_res]
451 expr_code = u' + '.join(gen_sig_code(cache_spec))
452 signature_id_tuple = '(%s)' % (
453 ', '.join(compat_str(len(p)) for p in example_sig.split('.')))
454 code = (u'if tuple(len(p) for p in s.split(\'.\')) == %s:\n'
455 u' return %s\n') % (signature_id_tuple, expr_code)
456 self.to_screen(u'Extracted signature function:\n' + code)
458 def _parse_sig_js(self, jscode):
459 funcname = self._search_regex(
460 r'signature=([$a-zA-Z]+)', jscode,
461 u'Initial JS player signature function name')
463 jsi = JSInterpreter(jscode)
464 initial_function = jsi.extract_function(funcname)
465 return lambda s: initial_function([s])
467 def _parse_sig_swf(self, file_contents):
468 swfi = SWFInterpreter(file_contents)
469 TARGET_CLASSNAME = u'SignatureDecipher'
470 searched_class = swfi.extract_class(TARGET_CLASSNAME)
471 initial_function = swfi.extract_function(searched_class, u'decipher')
472 return lambda s: initial_function([s])
474 def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
475 """Turn the encrypted s field into a working signature"""
477 if player_url is None:
478 raise ExtractorError(u'Cannot decrypt signature without player_url')
480 if player_url.startswith(u'//'):
481 player_url = u'https:' + player_url
483 player_id = (player_url, self._signature_cache_id(s))
484 if player_id not in self._player_cache:
485 func = self._extract_signature_function(
486 video_id, player_url, s
488 self._player_cache[player_id] = func
489 func = self._player_cache[player_id]
490 if self._downloader.params.get('youtube_print_sig_code'):
491 self._print_sig_code(func, s)
493 except Exception as e:
494 tb = traceback.format_exc()
495 raise ExtractorError(
496 u'Signature extraction failed: ' + tb, cause=e)
498 def _get_available_subtitles(self, video_id, webpage):
500 sub_list = self._download_webpage(
501 'https://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
502 video_id, note=False)
503 except ExtractorError as err:
504 self._downloader.report_warning(u'unable to download video subtitles: %s' % compat_str(err))
506 lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list)
511 params = compat_urllib_parse.urlencode({
514 'fmt': self._downloader.params.get('subtitlesformat', 'srt'),
515 'name': unescapeHTML(l[0]).encode('utf-8'),
517 url = u'https://www.youtube.com/api/timedtext?' + params
518 sub_lang_list[lang] = url
519 if not sub_lang_list:
520 self._downloader.report_warning(u'video doesn\'t have subtitles')
524 def _get_available_automatic_caption(self, video_id, webpage):
525 """We need the webpage for getting the captions url, pass it as an
526 argument to speed up the process."""
527 sub_format = self._downloader.params.get('subtitlesformat', 'srt')
528 self.to_screen(u'%s: Looking for automatic captions' % video_id)
529 mobj = re.search(r';ytplayer.config = ({.*?});', webpage)
530 err_msg = u'Couldn\'t find automatic captions for %s' % video_id
532 self._downloader.report_warning(err_msg)
534 player_config = json.loads(mobj.group(1))
536 args = player_config[u'args']
537 caption_url = args[u'ttsurl']
538 timestamp = args[u'timestamp']
539 # We get the available subtitles
540 list_params = compat_urllib_parse.urlencode({
545 list_url = caption_url + '&' + list_params
546 caption_list = self._download_xml(list_url, video_id)
547 original_lang_node = caption_list.find('track')
548 if original_lang_node is None or original_lang_node.attrib.get('kind') != 'asr' :
549 self._downloader.report_warning(u'Video doesn\'t have automatic captions')
551 original_lang = original_lang_node.attrib['lang_code']
554 for lang_node in caption_list.findall('target'):
555 sub_lang = lang_node.attrib['lang_code']
556 params = compat_urllib_parse.urlencode({
557 'lang': original_lang,
563 sub_lang_list[sub_lang] = caption_url + '&' + params
565 # An extractor error can be raise by the download process if there are
566 # no automatic captions but there are subtitles
567 except (KeyError, ExtractorError):
568 self._downloader.report_warning(err_msg)
572 def extract_id(cls, url):
573 mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
575 raise ExtractorError(u'Invalid URL: %s' % url)
576 video_id = mobj.group(2)
579 def _extract_from_m3u8(self, manifest_url, video_id):
581 def _get_urls(_manifest):
582 lines = _manifest.split('\n')
583 urls = filter(lambda l: l and not l.startswith('#'),
586 manifest = self._download_webpage(manifest_url, video_id, u'Downloading formats manifest')
587 formats_urls = _get_urls(manifest)
588 for format_url in formats_urls:
589 itag = self._search_regex(r'itag/(\d+?)/', format_url, 'itag')
590 url_map[itag] = format_url
593 def _extract_annotations(self, video_id):
594 url = 'https://www.youtube.com/annotations_invideo?features=1&legacy=1&video_id=%s' % video_id
595 return self._download_webpage(url, video_id, note=u'Searching for annotations.', errnote=u'Unable to download video annotations.')
597 def _real_extract(self, url):
599 u'http' if self._downloader.params.get('prefer_insecure', False)
602 # Extract original video URL from URL with redirection, like age verification, using next_url parameter
603 mobj = re.search(self._NEXT_URL_RE, url)
605 url = proto + '://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
606 video_id = self.extract_id(url)
609 url = proto + '://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
610 video_webpage = self._download_webpage(url, video_id)
612 # Attempt to extract SWF player URL
613 mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
615 player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
620 self.report_video_info_webpage_download(video_id)
621 if re.search(r'player-age-gate-content">', video_webpage) is not None:
622 self.report_age_confirmation()
624 # We simulate the access to the video from www.youtube.com/v/{video_id}
625 # this can be viewed without login into Youtube
626 data = compat_urllib_parse.urlencode({
627 'video_id': video_id,
628 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
629 'sts': self._search_regex(
630 r'"sts"\s*:\s*(\d+)', video_webpage, 'sts'),
632 video_info_url = proto + '://www.youtube.com/get_video_info?' + data
633 video_info_webpage = self._download_webpage(video_info_url, video_id,
635 errnote='unable to download video info webpage')
636 video_info = compat_parse_qs(video_info_webpage)
639 for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
640 video_info_url = (proto + '://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
641 % (video_id, el_type))
642 video_info_webpage = self._download_webpage(video_info_url, video_id,
644 errnote='unable to download video info webpage')
645 video_info = compat_parse_qs(video_info_webpage)
646 if 'token' in video_info:
648 if 'token' not in video_info:
649 if 'reason' in video_info:
650 raise ExtractorError(
651 u'YouTube said: %s' % video_info['reason'][0],
652 expected=True, video_id=video_id)
654 raise ExtractorError(
655 u'"token" parameter not in video info for unknown reason',
658 if 'view_count' in video_info:
659 view_count = int(video_info['view_count'][0])
663 # Check for "rental" videos
664 if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
665 raise ExtractorError(u'"rental" videos not supported')
667 # Start extracting information
668 self.report_information_extraction(video_id)
671 if 'author' not in video_info:
672 raise ExtractorError(u'Unable to extract uploader name')
673 video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
676 video_uploader_id = None
677 mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
679 video_uploader_id = mobj.group(1)
681 self._downloader.report_warning(u'unable to extract uploader nickname')
684 if 'title' in video_info:
685 video_title = video_info['title'][0]
687 self._downloader.report_warning(u'Unable to extract video title')
691 # We try first to get a high quality image:
692 m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
693 video_webpage, re.DOTALL)
694 if m_thumb is not None:
695 video_thumbnail = m_thumb.group(1)
696 elif 'thumbnail_url' not in video_info:
697 self._downloader.report_warning(u'unable to extract video thumbnail')
698 video_thumbnail = None
699 else: # don't panic if we can't find it
700 video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
704 mobj = re.search(r'(?s)id="eow-date.*?>(.*?)</span>', video_webpage)
707 r'(?s)id="watch-uploader-info".*?>.*?(?:Published|Uploaded|Streamed live) on (.*?)</strong>',
710 upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
711 upload_date = unified_strdate(upload_date)
713 m_cat_container = get_element_by_id("eow-category", video_webpage)
715 category = self._html_search_regex(
716 r'(?s)<a[^<]+>(.*?)</a>', m_cat_container, 'category',
718 video_categories = None if category is None else [category]
720 video_categories = None
723 video_description = get_element_by_id("eow-description", video_webpage)
724 if video_description:
725 video_description = re.sub(r'''(?x)
727 (?:[a-zA-Z-]+="[^"]+"\s+)*?
729 (?:[a-zA-Z-]+="[^"]+"\s+)*?
730 class="yt-uix-redirect-link"\s*>
733 ''', r'\1', video_description)
734 video_description = clean_html(video_description)
736 fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
738 video_description = unescapeHTML(fd_mobj.group(1))
740 video_description = u''
742 def _extract_count(klass):
743 count = self._search_regex(
744 r'class="%s">([\d,]+)</span>' % re.escape(klass),
745 video_webpage, klass, default=None)
746 if count is not None:
747 return int(count.replace(',', ''))
749 like_count = _extract_count(u'likes-count')
750 dislike_count = _extract_count(u'dislikes-count')
753 video_subtitles = self.extract_subtitles(video_id, video_webpage)
755 if self._downloader.params.get('listsubtitles', False):
756 self._list_available_subtitles(video_id, video_webpage)
759 if 'length_seconds' not in video_info:
760 self._downloader.report_warning(u'unable to extract video duration')
761 video_duration = None
763 video_duration = int(compat_urllib_parse.unquote_plus(video_info['length_seconds'][0]))
766 video_annotations = None
767 if self._downloader.params.get('writeannotations', False):
768 video_annotations = self._extract_annotations(video_id)
770 # Decide which formats to download
772 mobj = re.search(r';ytplayer\.config\s*=\s*({.*?});', video_webpage)
774 raise ValueError('Could not find vevo ID')
775 json_code = uppercase_escape(mobj.group(1))
776 ytplayer_config = json.loads(json_code)
777 args = ytplayer_config['args']
778 # Easy way to know if the 's' value is in url_encoded_fmt_stream_map
779 # this signatures are encrypted
780 if 'url_encoded_fmt_stream_map' not in args:
781 raise ValueError(u'No stream_map present') # caught below
782 re_signature = re.compile(r'[&,]s=')
783 m_s = re_signature.search(args['url_encoded_fmt_stream_map'])
785 self.to_screen(u'%s: Encrypted signatures detected.' % video_id)
786 video_info['url_encoded_fmt_stream_map'] = [args['url_encoded_fmt_stream_map']]
787 m_s = re_signature.search(args.get('adaptive_fmts', u''))
789 if 'adaptive_fmts' in video_info:
790 video_info['adaptive_fmts'][0] += ',' + args['adaptive_fmts']
792 video_info['adaptive_fmts'] = [args['adaptive_fmts']]
796 def _map_to_format_list(urlmap):
798 for itag, video_real_url in urlmap.items():
801 'url': video_real_url,
802 'player_url': player_url,
804 if itag in self._formats:
805 dct.update(self._formats[itag])
809 if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
810 self.report_rtmp_download()
812 'format_id': '_rtmp',
814 'url': video_info['conn'][0],
815 'player_url': player_url,
817 elif len(video_info.get('url_encoded_fmt_stream_map', [])) >= 1 or len(video_info.get('adaptive_fmts', [])) >= 1:
818 encoded_url_map = video_info.get('url_encoded_fmt_stream_map', [''])[0] + ',' + video_info.get('adaptive_fmts',[''])[0]
819 if 'rtmpe%3Dyes' in encoded_url_map:
820 raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True)
822 for url_data_str in encoded_url_map.split(','):
823 url_data = compat_parse_qs(url_data_str)
824 if 'itag' not in url_data or 'url' not in url_data:
826 format_id = url_data['itag'][0]
827 url = url_data['url'][0]
829 if 'sig' in url_data:
830 url += '&signature=' + url_data['sig'][0]
831 elif 's' in url_data:
832 encrypted_sig = url_data['s'][0]
835 jsplayer_url_json = self._search_regex(
836 r'"assets":.+?"js":\s*("[^"]+")',
837 video_webpage, u'JS player URL')
838 player_url = json.loads(jsplayer_url_json)
839 if player_url is None:
840 player_url_json = self._search_regex(
841 r'ytplayer\.config.*?"url"\s*:\s*("[^"]+")',
842 video_webpage, u'age gate player URL')
843 player_url = json.loads(player_url_json)
845 if self._downloader.params.get('verbose'):
846 if player_url is None:
847 player_version = 'unknown'
848 player_desc = 'unknown'
850 if player_url.endswith('swf'):
851 player_version = self._search_regex(
852 r'-(.+?)(?:/watch_as3)?\.swf$', player_url,
853 u'flash player', fatal=False)
854 player_desc = 'flash player %s' % player_version
856 player_version = self._search_regex(
857 r'html5player-([^/]+?)(?:/html5player)?\.js',
859 'html5 player', fatal=False)
860 player_desc = u'html5 player %s' % player_version
862 parts_sizes = self._signature_cache_id(encrypted_sig)
863 self.to_screen(u'{%s} signature length %s, %s' %
864 (format_id, parts_sizes, player_desc))
866 signature = self._decrypt_signature(
867 encrypted_sig, video_id, player_url, age_gate)
868 url += '&signature=' + signature
869 if 'ratebypass' not in url:
870 url += '&ratebypass=yes'
871 url_map[format_id] = url
872 formats = _map_to_format_list(url_map)
873 elif video_info.get('hlsvp'):
874 manifest_url = video_info['hlsvp'][0]
875 url_map = self._extract_from_m3u8(manifest_url, video_id)
876 formats = _map_to_format_list(url_map)
878 raise ExtractorError(u'no conn, hlsvp or url_encoded_fmt_stream_map information found in video info')
880 # Look for the DASH manifest
881 if (self._downloader.params.get('youtube_include_dash_manifest', False)):
883 # The DASH manifest used needs to be the one from the original video_webpage.
884 # The one found in get_video_info seems to be using different signatures.
885 # However, in the case of an age restriction there won't be any embedded dashmpd in the video_webpage.
886 # Luckily, it seems, this case uses some kind of default signature (len == 86), so the
887 # combination of get_video_info and the _static_decrypt_signature() decryption fallback will work here.
889 dash_manifest_url = video_info.get('dashmpd')[0]
891 dash_manifest_url = ytplayer_config['args']['dashmpd']
892 def decrypt_sig(mobj):
894 dec_s = self._decrypt_signature(s, video_id, player_url, age_gate)
895 return '/signature/%s' % dec_s
896 dash_manifest_url = re.sub(r'/s/([\w\.]+)', decrypt_sig, dash_manifest_url)
897 dash_doc = self._download_xml(
898 dash_manifest_url, video_id,
899 note=u'Downloading DASH manifest',
900 errnote=u'Could not download DASH manifest')
901 for r in dash_doc.findall(u'.//{urn:mpeg:DASH:schema:MPD:2011}Representation'):
902 url_el = r.find('{urn:mpeg:DASH:schema:MPD:2011}BaseURL')
905 format_id = r.attrib['id']
906 video_url = url_el.text
907 filesize = int_or_none(url_el.attrib.get('{http://youtube.com/yt/2012/10/10}contentLength'))
909 'format_id': format_id,
911 'width': int_or_none(r.attrib.get('width')),
912 'tbr': int_or_none(r.attrib.get('bandwidth'), 1000),
913 'asr': int_or_none(r.attrib.get('audioSamplingRate')),
914 'filesize': filesize,
917 existing_format = next(
919 if fo['format_id'] == format_id)
920 except StopIteration:
921 f.update(self._formats.get(format_id, {}))
924 existing_format.update(f)
926 except (ExtractorError, KeyError) as e:
927 self.report_warning(u'Skipping DASH manifest: %s' % e, video_id)
929 self._sort_formats(formats)
933 'uploader': video_uploader,
934 'uploader_id': video_uploader_id,
935 'upload_date': upload_date,
936 'title': video_title,
937 'thumbnail': video_thumbnail,
938 'description': video_description,
939 'categories': video_categories,
940 'subtitles': video_subtitles,
941 'duration': video_duration,
942 'age_limit': 18 if age_gate else 0,
943 'annotations': video_annotations,
944 'webpage_url': proto + '://www.youtube.com/watch?v=%s' % video_id,
945 'view_count': view_count,
946 'like_count': like_count,
947 'dislike_count': dislike_count,
951 class YoutubePlaylistIE(YoutubeBaseInfoExtractor):
952 IE_DESC = u'YouTube.com playlists'
953 _VALID_URL = r"""(?x)(?:
958 (?:course|view_play_list|my_playlists|artist|playlist|watch)
959 \? (?:.*?&)*? (?:p|a|list)=
963 (?:PL|LL|EC|UU|FL|RD)?[0-9A-Za-z-_]{10,}
964 # Top tracks, they can also include dots
969 ((?:PL|LL|EC|UU|FL|RD)[0-9A-Za-z-_]{10,})
971 _TEMPLATE_URL = 'https://www.youtube.com/playlist?list=%s'
972 _MORE_PAGES_INDICATOR = r'data-link-type="next"'
973 _VIDEO_RE = r'href="\s*/watch\?v=(?P<id>[0-9A-Za-z_-]{11})&[^"]*?index=(?P<index>\d+)'
974 IE_NAME = u'youtube:playlist'
976 def _real_initialize(self):
979 def _ids_to_results(self, ids):
980 return [self.url_result(vid_id, 'Youtube', video_id=vid_id)
983 def _extract_mix(self, playlist_id):
984 # The mixes are generated from a a single video
985 # the id of the playlist is just 'RD' + video_id
986 url = 'https://youtube.com/watch?v=%s&list=%s' % (playlist_id[-11:], playlist_id)
987 webpage = self._download_webpage(url, playlist_id, u'Downloading Youtube mix')
988 search_title = lambda class_name: get_element_by_attribute('class', class_name, webpage)
989 title_span = (search_title('playlist-title') or
990 search_title('title long-title') or search_title('title'))
991 title = clean_html(title_span)
992 video_re = r'''(?x)data-video-username=".*?".*?
993 href="/watch\?v=([0-9A-Za-z_-]{11})&[^"]*?list=%s''' % re.escape(playlist_id)
994 ids = orderedSet(re.findall(video_re, webpage, flags=re.DOTALL))
995 url_results = self._ids_to_results(ids)
997 return self.playlist_result(url_results, playlist_id, title)
999 def _real_extract(self, url):
1000 # Extract playlist id
1001 mobj = re.match(self._VALID_URL, url)
1003 raise ExtractorError(u'Invalid URL: %s' % url)
1004 playlist_id = mobj.group(1) or mobj.group(2)
1006 # Check if it's a video-specific URL
1007 query_dict = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
1008 if 'v' in query_dict:
1009 video_id = query_dict['v'][0]
1010 if self._downloader.params.get('noplaylist'):
1011 self.to_screen(u'Downloading just video %s because of --no-playlist' % video_id)
1012 return self.url_result(video_id, 'Youtube', video_id=video_id)
1014 self.to_screen(u'Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
1016 if playlist_id.startswith('RD'):
1017 # Mixes require a custom extraction process
1018 return self._extract_mix(playlist_id)
1019 if playlist_id.startswith('TL'):
1020 raise ExtractorError(u'For downloading YouTube.com top lists, use '
1021 u'the "yttoplist" keyword, for example "youtube-dl \'yttoplist:music:Top Tracks\'"', expected=True)
1023 url = self._TEMPLATE_URL % playlist_id
1024 page = self._download_webpage(url, playlist_id)
1025 more_widget_html = content_html = page
1027 # Check if the playlist exists or is private
1028 if re.search(r'<div class="yt-alert-message">[^<]*?(The|This) playlist (does not exist|is private)[^<]*?</div>', page) is not None:
1029 raise ExtractorError(
1030 u'The playlist doesn\'t exist or is private, use --username or '
1031 '--netrc to access it.',
1034 # Extract the video ids from the playlist pages
1037 for page_num in itertools.count(1):
1038 matches = re.finditer(self._VIDEO_RE, content_html)
1039 # We remove the duplicates and the link with index 0
1040 # (it's not the first video of the playlist)
1041 new_ids = orderedSet(m.group('id') for m in matches if m.group('index') != '0')
1044 mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
1048 more = self._download_json(
1049 'https://youtube.com/%s' % mobj.group('more'), playlist_id,
1050 'Downloading page #%s' % page_num,
1051 transform_source=uppercase_escape)
1052 content_html = more['content_html']
1053 more_widget_html = more['load_more_widget_html']
1055 playlist_title = self._html_search_regex(
1056 r'(?s)<h1 class="pl-header-title[^"]*">\s*(.*?)\s*</h1>',
1059 url_results = self._ids_to_results(ids)
1060 return self.playlist_result(url_results, playlist_id, playlist_title)
1063 class YoutubeTopListIE(YoutubePlaylistIE):
1064 IE_NAME = u'youtube:toplist'
1065 IE_DESC = (u'YouTube.com top lists, "yttoplist:{channel}:{list title}"'
1066 u' (Example: "yttoplist:music:Top Tracks")')
1067 _VALID_URL = r'yttoplist:(?P<chann>.*?):(?P<title>.*?)$'
1069 def _real_extract(self, url):
1070 mobj = re.match(self._VALID_URL, url)
1071 channel = mobj.group('chann')
1072 title = mobj.group('title')
1073 query = compat_urllib_parse.urlencode({'title': title})
1074 playlist_re = 'href="([^"]+?%s.*?)"' % re.escape(query)
1075 channel_page = self._download_webpage('https://www.youtube.com/%s' % channel, title)
1076 link = self._html_search_regex(playlist_re, channel_page, u'list')
1077 url = compat_urlparse.urljoin('https://www.youtube.com/', link)
1079 video_re = r'data-index="\d+".*?data-video-id="([0-9A-Za-z_-]{11})"'
1081 # sometimes the webpage doesn't contain the videos
1082 # retry until we get them
1083 for i in itertools.count(0):
1084 msg = u'Downloading Youtube mix'
1086 msg += ', retry #%d' % i
1087 webpage = self._download_webpage(url, title, msg)
1088 ids = orderedSet(re.findall(video_re, webpage))
1091 url_results = self._ids_to_results(ids)
1092 return self.playlist_result(url_results, playlist_title=title)
1095 class YoutubeChannelIE(InfoExtractor):
1096 IE_DESC = u'YouTube.com channels'
1097 _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)"
1098 _MORE_PAGES_INDICATOR = 'yt-uix-load-more'
1099 _MORE_PAGES_URL = 'https://www.youtube.com/c4_browse_ajax?action_load_more_videos=1&flow=list&paging=%s&view=0&sort=da&channel_id=%s'
1100 IE_NAME = u'youtube:channel'
1102 def extract_videos_from_page(self, page):
1104 for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&?', page):
1105 if mobj.group(1) not in ids_in_page:
1106 ids_in_page.append(mobj.group(1))
1109 def _real_extract(self, url):
1110 # Extract channel id
1111 mobj = re.match(self._VALID_URL, url)
1113 raise ExtractorError(u'Invalid URL: %s' % url)
1115 # Download channel page
1116 channel_id = mobj.group(1)
1118 url = 'https://www.youtube.com/channel/%s/videos' % channel_id
1119 channel_page = self._download_webpage(url, channel_id)
1120 autogenerated = re.search(r'''(?x)
1122 channel-header-autogenerated-label|
1123 yt-channel-title-autogenerated
1124 )[^"]*"''', channel_page) is not None
1127 # The videos are contained in a single page
1128 # the ajax pages can't be used, they are empty
1129 video_ids = self.extract_videos_from_page(channel_page)
1131 # Download all channel pages using the json-based channel_ajax query
1132 for pagenum in itertools.count(1):
1133 url = self._MORE_PAGES_URL % (pagenum, channel_id)
1134 page = self._download_json(
1135 url, channel_id, note=u'Downloading page #%s' % pagenum,
1136 transform_source=uppercase_escape)
1138 ids_in_page = self.extract_videos_from_page(page['content_html'])
1139 video_ids.extend(ids_in_page)
1141 if self._MORE_PAGES_INDICATOR not in page['load_more_widget_html']:
1144 self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
1146 url_entries = [self.url_result(video_id, 'Youtube', video_id=video_id)
1147 for video_id in video_ids]
1148 return self.playlist_result(url_entries, channel_id)
1151 class YoutubeUserIE(InfoExtractor):
1152 IE_DESC = u'YouTube.com user videos (URL or "ytuser" keyword)'
1153 _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/(?:user/)?(?!(?:attribution_link|watch|results)(?:$|[^a-z_A-Z0-9-])))|ytuser:)(?!feed/)([A-Za-z0-9_-]+)'
1154 _TEMPLATE_URL = 'https://gdata.youtube.com/feeds/api/users/%s'
1155 _GDATA_PAGE_SIZE = 50
1156 _GDATA_URL = 'https://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d&alt=json'
1157 IE_NAME = u'youtube:user'
1160 def suitable(cls, url):
1161 # Don't return True if the url can be extracted with other youtube
1162 # extractor, the regex would is too permissive and it would match.
1163 other_ies = iter(klass for (name, klass) in globals().items() if name.endswith('IE') and klass is not cls)
1164 if any(ie.suitable(url) for ie in other_ies): return False
1165 else: return super(YoutubeUserIE, cls).suitable(url)
1167 def _real_extract(self, url):
1169 mobj = re.match(self._VALID_URL, url)
1171 raise ExtractorError(u'Invalid URL: %s' % url)
1173 username = mobj.group(1)
1175 # Download video ids using YouTube Data API. Result size per
1176 # query is limited (currently to 50 videos) so we need to query
1177 # page by page until there are no video ids - it means we got
1180 def download_page(pagenum):
1181 start_index = pagenum * self._GDATA_PAGE_SIZE + 1
1183 gdata_url = self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index)
1184 page = self._download_webpage(
1185 gdata_url, username,
1186 u'Downloading video ids from %d to %d' % (
1187 start_index, start_index + self._GDATA_PAGE_SIZE))
1190 response = json.loads(page)
1191 except ValueError as err:
1192 raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err))
1193 if 'entry' not in response['feed']:
1196 # Extract video identifiers
1197 entries = response['feed']['entry']
1198 for entry in entries:
1199 title = entry['title']['$t']
1200 video_id = entry['id']['$t'].split('/')[-1]
1204 'ie_key': 'Youtube',
1208 url_results = PagedList(download_page, self._GDATA_PAGE_SIZE)
1210 return self.playlist_result(url_results, playlist_title=username)
1213 class YoutubeSearchIE(SearchInfoExtractor):
1214 IE_DESC = u'YouTube.com searches'
1215 _API_URL = u'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
1217 IE_NAME = u'youtube:search'
1218 _SEARCH_KEY = 'ytsearch'
1220 def _get_n_results(self, query, n):
1221 """Get a specified number of results for a query"""
1228 while (PAGE_SIZE * pagenum) < limit:
1229 result_url = self._API_URL % (
1230 compat_urllib_parse.quote_plus(query.encode('utf-8')),
1231 (PAGE_SIZE * pagenum) + 1)
1232 data_json = self._download_webpage(
1233 result_url, video_id=u'query "%s"' % query,
1234 note=u'Downloading page %s' % (pagenum + 1),
1235 errnote=u'Unable to download API page')
1236 data = json.loads(data_json)
1237 api_response = data['data']
1239 if 'items' not in api_response:
1240 raise ExtractorError(
1241 u'[youtube] No video results', expected=True)
1243 new_ids = list(video['id'] for video in api_response['items'])
1244 video_ids += new_ids
1246 limit = min(n, api_response['totalItems'])
1249 if len(video_ids) > n:
1250 video_ids = video_ids[:n]
1251 videos = [self.url_result(video_id, 'Youtube', video_id=video_id)
1252 for video_id in video_ids]
1253 return self.playlist_result(videos, query)
1256 class YoutubeSearchDateIE(YoutubeSearchIE):
1257 IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
1258 _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc&orderby=published'
1259 _SEARCH_KEY = 'ytsearchdate'
1260 IE_DESC = u'YouTube.com searches, newest videos first'
1263 class YoutubeSearchURLIE(InfoExtractor):
1264 IE_DESC = u'YouTube.com search URLs'
1265 IE_NAME = u'youtube:search_url'
1266 _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?search_query=(?P<query>[^&]+)(?:[&]|$)'
1268 def _real_extract(self, url):
1269 mobj = re.match(self._VALID_URL, url)
1270 query = compat_urllib_parse.unquote_plus(mobj.group('query'))
1272 webpage = self._download_webpage(url, query)
1273 result_code = self._search_regex(
1274 r'(?s)<ol class="item-section"(.*?)</ol>', webpage, u'result HTML')
1276 part_codes = re.findall(
1277 r'(?s)<h3 class="yt-lockup-title">(.*?)</h3>', result_code)
1279 for part_code in part_codes:
1280 part_title = self._html_search_regex(
1281 [r'(?s)title="([^"]+)"', r'>([^<]+)</a>'], part_code, 'item title', fatal=False)
1282 part_url_snippet = self._html_search_regex(
1283 r'(?s)href="([^"]+)"', part_code, 'item URL')
1284 part_url = compat_urlparse.urljoin(
1285 'https://www.youtube.com/', part_url_snippet)
1289 'title': part_title,
1293 '_type': 'playlist',
1299 class YoutubeShowIE(InfoExtractor):
1300 IE_DESC = u'YouTube.com (multi-season) shows'
1301 _VALID_URL = r'https?://www\.youtube\.com/show/(.*)'
1302 IE_NAME = u'youtube:show'
1304 def _real_extract(self, url):
1305 mobj = re.match(self._VALID_URL, url)
1306 show_name = mobj.group(1)
1307 webpage = self._download_webpage(url, show_name, u'Downloading show webpage')
1308 # There's one playlist for each season of the show
1309 m_seasons = list(re.finditer(r'href="(/playlist\?list=.*?)"', webpage))
1310 self.to_screen(u'%s: Found %s seasons' % (show_name, len(m_seasons)))
1311 return [self.url_result('https://www.youtube.com' + season.group(1), 'YoutubePlaylist') for season in m_seasons]
1314 class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
1316 Base class for extractors that fetch info from
1317 http://www.youtube.com/feed_ajax
1318 Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
1320 _LOGIN_REQUIRED = True
1321 # use action_load_personal_feed instead of action_load_system_feed
1322 _PERSONAL_FEED = False
1325 def _FEED_TEMPLATE(self):
1326 action = 'action_load_system_feed'
1327 if self._PERSONAL_FEED:
1328 action = 'action_load_personal_feed'
1329 return 'https://www.youtube.com/feed_ajax?%s=1&feed_name=%s&paging=%%s' % (action, self._FEED_NAME)
1333 return u'youtube:%s' % self._FEED_NAME
1335 def _real_initialize(self):
1338 def _real_extract(self, url):
1341 for i in itertools.count(1):
1342 info = self._download_json(self._FEED_TEMPLATE % paging,
1343 u'%s feed' % self._FEED_NAME,
1344 u'Downloading page %s' % i)
1345 feed_html = info.get('feed_html') or info.get('content_html')
1346 m_ids = re.finditer(r'"/watch\?v=(.*?)["&]', feed_html)
1347 ids = orderedSet(m.group(1) for m in m_ids)
1348 feed_entries.extend(
1349 self.url_result(video_id, 'Youtube', video_id=video_id)
1350 for video_id in ids)
1352 r'data-uix-load-more-href="/?[^"]+paging=(?P<paging>\d+)',
1356 paging = mobj.group('paging')
1357 return self.playlist_result(feed_entries, playlist_title=self._PLAYLIST_TITLE)
1359 class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
1360 IE_DESC = u'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)'
1361 _VALID_URL = r'https?://www\.youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
1362 _FEED_NAME = 'subscriptions'
1363 _PLAYLIST_TITLE = u'Youtube Subscriptions'
1365 class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
1366 IE_DESC = u'YouTube.com recommended videos, "ytrec" keyword (requires authentication)'
1367 _VALID_URL = r'https?://www\.youtube\.com/feed/recommended|:ytrec(?:ommended)?'
1368 _FEED_NAME = 'recommended'
1369 _PLAYLIST_TITLE = u'Youtube Recommended videos'
1371 class YoutubeWatchLaterIE(YoutubeFeedsInfoExtractor):
1372 IE_DESC = u'Youtube watch later list, "ytwatchlater" keyword (requires authentication)'
1373 _VALID_URL = r'https?://www\.youtube\.com/feed/watch_later|:ytwatchlater'
1374 _FEED_NAME = 'watch_later'
1375 _PLAYLIST_TITLE = u'Youtube Watch Later'
1376 _PERSONAL_FEED = True
1378 class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
1379 IE_DESC = u'Youtube watch history, "ythistory" keyword (requires authentication)'
1380 _VALID_URL = u'https?://www\.youtube\.com/feed/history|:ythistory'
1381 _FEED_NAME = 'history'
1382 _PERSONAL_FEED = True
1383 _PLAYLIST_TITLE = u'Youtube Watch History'
1385 class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
1386 IE_NAME = u'youtube:favorites'
1387 IE_DESC = u'YouTube.com favourite videos, "ytfav" keyword (requires authentication)'
1388 _VALID_URL = r'https?://www\.youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
1389 _LOGIN_REQUIRED = True
1391 def _real_extract(self, url):
1392 webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
1393 playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, u'favourites playlist id')
1394 return self.url_result(playlist_id, 'YoutubePlaylist')
1397 class YoutubeTruncatedURLIE(InfoExtractor):
1398 IE_NAME = 'youtube:truncated_url'
1399 IE_DESC = False # Do not list
1400 _VALID_URL = r'''(?x)
1401 (?:https?://)?[^/]+/watch\?(?:
1403 annotation_id=annotation_[^&]+
1405 (?:https?://)?(?:www\.)?youtube\.com/attribution_link\?a=[^&]+$
1409 'url': 'http://www.youtube.com/watch?annotation_id=annotation_3951667041',
1410 'only_matching': True,
1412 'url': 'http://www.youtube.com/watch?',
1413 'only_matching': True,
1416 def _real_extract(self, url):
1417 raise ExtractorError(
1418 u'Did you forget to quote the URL? Remember that & is a meta '
1419 u'character in most shells, so you want to put the URL in quotes, '
1421 u'"http://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
1422 u' or simply youtube-dl BaW_jenozKc .',