8 from .common import InfoExtractor, SearchInfoExtractor
14 compat_urllib_request,
25 class YoutubeIE(InfoExtractor):
26 """Information extractor for youtube.com."""
30 (?:https?://)? # http(s):// (optional)
31 (?:youtu\.be/|(?:\w+\.)?youtube(?:-nocookie)?\.com/|
32 tube\.majestyc\.net/) # the various hostnames, with wildcard subdomains
33 (?:.*?\#/)? # handle anchor (#/) redirect urls
34 (?: # the various things that can precede the ID:
35 (?:(?:v|embed|e)/) # v/ or embed/ or e/
36 |(?: # or the v= param in all its forms
37 (?:watch(?:_popup)?(?:\.php)?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
38 (?:\?|\#!?) # the params delimiter ? or # or #!
39 (?:.*?&)? # any other preceding param (like /?s=tuff&v=xxxx)
42 )? # optional -> youtube.com/xxxx is OK
43 )? # all until now is optional -> you can pass the naked ID
44 ([0-9A-Za-z_-]+) # here is it! the YouTube video ID
45 (?(1).+)? # if we found the ID, everything can follow
47 _LANG_URL = r'https://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
48 _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
49 _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
50 _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
51 _NETRC_MACHINE = 'youtube'
52 # Listed in order of quality
53 _available_formats = ['38', '37', '46', '22', '45', '35', '44', '34', '18', '43', '6', '5', '17', '13']
54 _available_formats_prefer_free = ['38', '46', '37', '45', '22', '44', '35', '43', '34', '18', '6', '5', '17', '13']
86 def suitable(cls, url):
87 """Receives a URL and returns True if suitable for this IE."""
88 if YoutubePlaylistIE.suitable(url): return False
89 return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
91 def report_lang(self):
92 """Report attempt to set language."""
93 self.to_screen(u'Setting language')
95 def report_login(self):
96 """Report attempt to log in."""
97 self.to_screen(u'Logging in')
99 def report_video_webpage_download(self, video_id):
100 """Report attempt to download video webpage."""
101 self.to_screen(u'%s: Downloading video webpage' % video_id)
103 def report_video_info_webpage_download(self, video_id):
104 """Report attempt to download video info webpage."""
105 self.to_screen(u'%s: Downloading video info webpage' % video_id)
107 def report_video_subtitles_download(self, video_id):
108 """Report attempt to download video info webpage."""
109 self.to_screen(u'%s: Checking available subtitles' % video_id)
111 def report_video_subtitles_request(self, video_id, sub_lang, format):
112 """Report attempt to download video info webpage."""
113 self.to_screen(u'%s: Downloading video subtitles for %s.%s' % (video_id, sub_lang, format))
115 def report_video_subtitles_available(self, video_id, sub_lang_list):
116 """Report available subtitles."""
117 sub_lang = ",".join(list(sub_lang_list.keys()))
118 self.to_screen(u'%s: Available subtitles for video: %s' % (video_id, sub_lang))
120 def report_information_extraction(self, video_id):
121 """Report attempt to extract video information."""
122 self.to_screen(u'%s: Extracting video information' % video_id)
124 def report_unavailable_format(self, video_id, format):
125 """Report extracted video URL."""
126 self.to_screen(u'%s: Format %s not available' % (video_id, format))
128 def report_rtmp_download(self):
129 """Indicate the download will use the RTMP protocol."""
130 self.to_screen(u'RTMP download detected')
132 def _decrypt_signature(self, s):
133 """Decrypt the key the two subkeys must have a length of 43"""
136 return s[48] + s[81:67:-1] + s[82] + s[66:62:-1] + s[85] + s[61:48:-1] + s[67] + s[47:12:-1] + s[3] + s[11:3:-1] + s[2] + s[12]
138 return s[62] + s[82:62:-1] + s[83] + s[61:52:-1] + s[0] + s[51:2:-1]
140 return s[2:63] + s[82] + s[64:82] + s[63]
142 return s[76] + s[82:76:-1] + s[83] + s[75:60:-1] + s[0] + s[59:50:-1] + s[1] + s[49:2:-1]
144 return s[83:36:-1] + s[2] + s[35:26:-1] + s[3] + s[25:3:-1] + s[26]
146 return s[52] + s[81:55:-1] + s[2] + s[54:52:-1] + s[82] + s[51:36:-1] + s[55] + s[35:2:-1] + s[36]
148 return s[36] + s[79:67:-1] + s[81] + s[66:40:-1] + s[33] + s[39:36:-1] + s[40] + s[35] + s[0] + s[67] + s[32:0:-1] + s[34]
151 raise ExtractorError(u'Unable to decrypt signature, subkeys length %d not supported; retrying might work' % (len(s)))
153 def _get_available_subtitles(self, video_id):
154 self.report_video_subtitles_download(video_id)
155 request = compat_urllib_request.Request('http://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id)
157 sub_list = compat_urllib_request.urlopen(request).read().decode('utf-8')
158 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
159 return (u'unable to download video subtitles: %s' % compat_str(err), None)
160 sub_lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list)
161 sub_lang_list = dict((l[1], l[0]) for l in sub_lang_list)
162 if not sub_lang_list:
163 return (u'video doesn\'t have subtitles', None)
166 def _list_available_subtitles(self, video_id):
167 sub_lang_list = self._get_available_subtitles(video_id)
168 self.report_video_subtitles_available(video_id, sub_lang_list)
170 def _request_subtitle(self, sub_lang, sub_name, video_id, format):
173 (error_message, sub_lang, sub)
175 self.report_video_subtitles_request(video_id, sub_lang, format)
176 params = compat_urllib_parse.urlencode({
182 url = 'http://www.youtube.com/api/timedtext?' + params
184 sub = compat_urllib_request.urlopen(url).read().decode('utf-8')
185 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
186 return (u'unable to download video subtitles: %s' % compat_str(err), None, None)
188 return (u'Did not fetch video subtitles', None, None)
189 return (None, sub_lang, sub)
191 def _request_automatic_caption(self, video_id, webpage):
192 """We need the webpage for getting the captions url, pass it as an
193 argument to speed up the process."""
194 sub_lang = self._downloader.params.get('subtitleslang') or 'en'
195 sub_format = self._downloader.params.get('subtitlesformat')
196 self.to_screen(u'%s: Looking for automatic captions' % video_id)
197 mobj = re.search(r';ytplayer.config = ({.*?});', webpage)
198 err_msg = u'Couldn\'t find automatic captions for "%s"' % sub_lang
200 return [(err_msg, None, None)]
201 player_config = json.loads(mobj.group(1))
203 args = player_config[u'args']
204 caption_url = args[u'ttsurl']
205 timestamp = args[u'timestamp']
206 params = compat_urllib_parse.urlencode({
213 subtitles_url = caption_url + '&' + params
214 sub = self._download_webpage(subtitles_url, video_id, u'Downloading automatic captions')
215 return [(None, sub_lang, sub)]
217 return [(err_msg, None, None)]
219 def _extract_subtitle(self, video_id):
221 Return a list with a tuple:
222 [(error_message, sub_lang, sub)]
224 sub_lang_list = self._get_available_subtitles(video_id)
225 sub_format = self._downloader.params.get('subtitlesformat')
226 if isinstance(sub_lang_list,tuple): #There was some error, it didn't get the available subtitles
227 return [(sub_lang_list[0], None, None)]
228 if self._downloader.params.get('subtitleslang', False):
229 sub_lang = self._downloader.params.get('subtitleslang')
230 elif 'en' in sub_lang_list:
233 sub_lang = list(sub_lang_list.keys())[0]
234 if not sub_lang in sub_lang_list:
235 return [(u'no closed captions found in the specified language "%s"' % sub_lang, None, None)]
237 subtitle = self._request_subtitle(sub_lang, sub_lang_list[sub_lang].encode('utf-8'), video_id, sub_format)
240 def _extract_all_subtitles(self, video_id):
241 sub_lang_list = self._get_available_subtitles(video_id)
242 sub_format = self._downloader.params.get('subtitlesformat')
243 if isinstance(sub_lang_list,tuple): #There was some error, it didn't get the available subtitles
244 return [(sub_lang_list[0], None, None)]
246 for sub_lang in sub_lang_list:
247 subtitle = self._request_subtitle(sub_lang, sub_lang_list[sub_lang].encode('utf-8'), video_id, sub_format)
248 subtitles.append(subtitle)
251 def _print_formats(self, formats):
252 print('Available formats:')
254 print('%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'flv'), self._video_dimensions.get(x, '???')))
256 def _real_initialize(self):
257 if self._downloader is None:
262 downloader_params = self._downloader.params
264 # Attempt to use provided username and password or .netrc data
265 if downloader_params.get('username', None) is not None:
266 username = downloader_params['username']
267 password = downloader_params['password']
268 elif downloader_params.get('usenetrc', False):
270 info = netrc.netrc().authenticators(self._NETRC_MACHINE)
275 raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
276 except (IOError, netrc.NetrcParseError) as err:
277 self._downloader.report_warning(u'parsing .netrc: %s' % compat_str(err))
281 request = compat_urllib_request.Request(self._LANG_URL)
284 compat_urllib_request.urlopen(request).read()
285 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
286 self._downloader.report_warning(u'unable to set language: %s' % compat_str(err))
289 # No authentication to be performed
293 request = compat_urllib_request.Request(self._LOGIN_URL)
295 login_page = compat_urllib_request.urlopen(request).read().decode('utf-8')
296 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
297 self._downloader.report_warning(u'unable to fetch login page: %s' % compat_str(err))
302 match = re.search(re.compile(r'<input.+?name="GALX".+?value="(.+?)"', re.DOTALL), login_page)
304 galx = match.group(1)
306 match = re.search(re.compile(r'<input.+?name="dsh".+?value="(.+?)"', re.DOTALL), login_page)
312 u'continue': u'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
316 u'PersistentCookie': u'yes',
318 u'bgresponse': u'js_disabled',
319 u'checkConnection': u'',
320 u'checkedDomains': u'youtube',
326 u'signIn': u'Sign in',
328 u'service': u'youtube',
332 # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
334 login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k,v in login_form_strs.items())
335 login_data = compat_urllib_parse.urlencode(login_form).encode('ascii')
336 request = compat_urllib_request.Request(self._LOGIN_URL, login_data)
339 login_results = compat_urllib_request.urlopen(request).read().decode('utf-8')
340 if re.search(r'(?i)<form[^>]* id="gaia_loginform"', login_results) is not None:
341 self._downloader.report_warning(u'unable to log in: bad username or password')
343 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
344 self._downloader.report_warning(u'unable to log in: %s' % compat_str(err))
350 'action_confirm': 'Confirm',
352 request = compat_urllib_request.Request(self._AGE_URL, compat_urllib_parse.urlencode(age_form))
354 self.report_age_confirmation()
355 compat_urllib_request.urlopen(request).read().decode('utf-8')
356 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
357 raise ExtractorError(u'Unable to confirm age: %s' % compat_str(err))
359 def _extract_id(self, url):
360 mobj = re.match(self._VALID_URL, url, re.VERBOSE)
362 raise ExtractorError(u'Invalid URL: %s' % url)
363 video_id = mobj.group(2)
366 def _real_extract(self, url):
367 # Extract original video URL from URL with redirection, like age verification, using next_url parameter
368 mobj = re.search(self._NEXT_URL_RE, url)
370 url = 'https://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
371 video_id = self._extract_id(url)
374 self.report_video_webpage_download(video_id)
375 url = 'https://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
376 request = compat_urllib_request.Request(url)
378 video_webpage_bytes = compat_urllib_request.urlopen(request).read()
379 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
380 raise ExtractorError(u'Unable to download video webpage: %s' % compat_str(err))
382 video_webpage = video_webpage_bytes.decode('utf-8', 'ignore')
384 # Attempt to extract SWF player URL
385 mobj = re.search(r'swfConfig.*?"(http:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
387 player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
392 self.report_video_info_webpage_download(video_id)
393 for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
394 video_info_url = ('https://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
395 % (video_id, el_type))
396 video_info_webpage = self._download_webpage(video_info_url, video_id,
398 errnote='unable to download video info webpage')
399 video_info = compat_parse_qs(video_info_webpage)
400 if 'token' in video_info:
402 if 'token' not in video_info:
403 if 'reason' in video_info:
404 raise ExtractorError(u'YouTube said: %s' % video_info['reason'][0])
406 raise ExtractorError(u'"token" parameter not in video info for unknown reason')
408 # Check for "rental" videos
409 if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
410 raise ExtractorError(u'"rental" videos not supported')
412 # Start extracting information
413 self.report_information_extraction(video_id)
416 if 'author' not in video_info:
417 raise ExtractorError(u'Unable to extract uploader name')
418 video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
421 video_uploader_id = None
422 mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
424 video_uploader_id = mobj.group(1)
426 self._downloader.report_warning(u'unable to extract uploader nickname')
429 if 'title' not in video_info:
430 raise ExtractorError(u'Unable to extract video title')
431 video_title = compat_urllib_parse.unquote_plus(video_info['title'][0])
434 if 'thumbnail_url' not in video_info:
435 self._downloader.report_warning(u'unable to extract video thumbnail')
437 else: # don't panic if we can't find it
438 video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
442 mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL)
444 upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
445 upload_date = unified_strdate(upload_date)
448 video_description = get_element_by_id("eow-description", video_webpage)
449 if video_description:
450 video_description = clean_html(video_description)
452 fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
454 video_description = unescapeHTML(fd_mobj.group(1))
456 video_description = u''
459 video_subtitles = None
461 if self._downloader.params.get('writesubtitles', False):
462 video_subtitles = self._extract_subtitle(video_id)
464 (sub_error, sub_lang, sub) = video_subtitles[0]
466 self._downloader.report_warning(sub_error)
468 if self._downloader.params.get('writeautomaticsub', False):
469 video_subtitles = self._request_automatic_caption(video_id, video_webpage)
470 (sub_error, sub_lang, sub) = video_subtitles[0]
472 self._downloader.report_warning(sub_error)
474 if self._downloader.params.get('allsubtitles', False):
475 video_subtitles = self._extract_all_subtitles(video_id)
476 for video_subtitle in video_subtitles:
477 (sub_error, sub_lang, sub) = video_subtitle
479 self._downloader.report_warning(sub_error)
481 if self._downloader.params.get('listsubtitles', False):
482 self._list_available_subtitles(video_id)
485 if 'length_seconds' not in video_info:
486 self._downloader.report_warning(u'unable to extract video duration')
489 video_duration = compat_urllib_parse.unquote_plus(video_info['length_seconds'][0])
491 # Decide which formats to download
492 req_format = self._downloader.params.get('format', None)
495 mobj = re.search(r';ytplayer.config = ({.*?});', video_webpage)
497 raise ValueError('Could not find vevo ID')
498 info = json.loads(mobj.group(1))
500 # Easy way to know if the 's' value is in url_encoded_fmt_stream_map
501 # this signatures are encrypted
502 m_s = re.search(r'[&,]s=', args['url_encoded_fmt_stream_map'])
504 self.to_screen(u'%s: Encrypted signatures detected.' % video_id)
505 video_info['url_encoded_fmt_stream_map'] = [args['url_encoded_fmt_stream_map']]
509 if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
510 self.report_rtmp_download()
511 video_url_list = [(None, video_info['conn'][0])]
512 elif 'url_encoded_fmt_stream_map' in video_info and len(video_info['url_encoded_fmt_stream_map']) >= 1:
514 for url_data_str in video_info['url_encoded_fmt_stream_map'][0].split(','):
515 url_data = compat_parse_qs(url_data_str)
516 if 'itag' in url_data and 'url' in url_data:
517 url = url_data['url'][0]
518 if 'sig' in url_data:
519 url += '&signature=' + url_data['sig'][0]
520 elif 's' in url_data:
521 if self._downloader.params.get('verbose'):
523 player = self._search_regex(r'html5player-(.+?)\.js', video_webpage,
524 'html5 player', fatal=False)
525 self.to_screen('encrypted signature length %d (%d.%d), itag %s, html5 player %s' %
526 (len(s), len(s.split('.')[0]), len(s.split('.')[1]), url_data['itag'][0], player))
527 signature = self._decrypt_signature(url_data['s'][0])
528 url += '&signature=' + signature
529 if 'ratebypass' not in url:
530 url += '&ratebypass=yes'
531 url_map[url_data['itag'][0]] = url
533 format_limit = self._downloader.params.get('format_limit', None)
534 available_formats = self._available_formats_prefer_free if self._downloader.params.get('prefer_free_formats', False) else self._available_formats
535 if format_limit is not None and format_limit in available_formats:
536 format_list = available_formats[available_formats.index(format_limit):]
538 format_list = available_formats
539 existing_formats = [x for x in format_list if x in url_map]
540 if len(existing_formats) == 0:
541 raise ExtractorError(u'no known formats available for video')
542 if self._downloader.params.get('listformats', None):
543 self._print_formats(existing_formats)
545 if req_format is None or req_format == 'best':
546 video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
547 elif req_format == 'worst':
548 video_url_list = [(existing_formats[len(existing_formats)-1], url_map[existing_formats[len(existing_formats)-1]])] # worst quality
549 elif req_format in ('-1', 'all'):
550 video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
552 # Specific formats. We pick the first in a slash-delimeted sequence.
553 # For example, if '1/2/3/4' is requested and '2' and '4' are available, we pick '2'.
554 req_formats = req_format.split('/')
555 video_url_list = None
556 for rf in req_formats:
558 video_url_list = [(rf, url_map[rf])]
560 if video_url_list is None:
561 raise ExtractorError(u'requested format not available')
563 raise ExtractorError(u'no conn or url_encoded_fmt_stream_map information found in video info')
566 for format_param, video_real_url in video_url_list:
568 video_extension = self._video_extensions.get(format_param, 'flv')
570 video_format = '{0} - {1}'.format(format_param if format_param else video_extension,
571 self._video_dimensions.get(format_param, '???'))
575 'url': video_real_url,
576 'uploader': video_uploader,
577 'uploader_id': video_uploader_id,
578 'upload_date': upload_date,
579 'title': video_title,
580 'ext': video_extension,
581 'format': video_format,
582 'thumbnail': video_thumbnail,
583 'description': video_description,
584 'player_url': player_url,
585 'subtitles': video_subtitles,
586 'duration': video_duration
590 class YoutubePlaylistIE(InfoExtractor):
591 """Information Extractor for YouTube playlists."""
598 (?:course|view_play_list|my_playlists|artist|playlist|watch)
599 \? (?:.*?&)*? (?:p|a|list)=
602 ((?:PL|EC|UU)?[0-9A-Za-z-_]{10,})
605 ((?:PL|EC|UU)[0-9A-Za-z-_]{10,})
607 _TEMPLATE_URL = 'https://gdata.youtube.com/feeds/api/playlists/%s?max-results=%i&start-index=%i&v=2&alt=json&safeSearch=none'
609 IE_NAME = u'youtube:playlist'
612 def suitable(cls, url):
613 """Receives a URL and returns True if suitable for this IE."""
614 return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
616 def _real_extract(self, url):
617 # Extract playlist id
618 mobj = re.match(self._VALID_URL, url, re.VERBOSE)
620 raise ExtractorError(u'Invalid URL: %s' % url)
622 # Download playlist videos from API
623 playlist_id = mobj.group(1) or mobj.group(2)
628 url = self._TEMPLATE_URL % (playlist_id, self._MAX_RESULTS, self._MAX_RESULTS * (page_num - 1) + 1)
629 page = self._download_webpage(url, playlist_id, u'Downloading page #%s' % page_num)
632 response = json.loads(page)
633 except ValueError as err:
634 raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err))
636 if 'feed' not in response:
637 raise ExtractorError(u'Got a malformed response from YouTube API')
638 playlist_title = response['feed']['title']['$t']
639 if 'entry' not in response['feed']:
640 # Number of videos is a multiple of self._MAX_RESULTS
643 for entry in response['feed']['entry']:
644 index = entry['yt$position']['$t']
645 if 'media$group' in entry and 'media$player' in entry['media$group']:
646 videos.append((index, entry['media$group']['media$player']['url']))
648 if len(response['feed']['entry']) < self._MAX_RESULTS:
652 videos = [v[1] for v in sorted(videos)]
654 url_results = [self.url_result(url, 'Youtube') for url in videos]
655 return [self.playlist_result(url_results, playlist_id, playlist_title)]
658 class YoutubeChannelIE(InfoExtractor):
659 """Information Extractor for YouTube channels."""
661 _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)"
662 _TEMPLATE_URL = 'http://www.youtube.com/channel/%s/videos?sort=da&flow=list&view=0&page=%s&gl=US&hl=en'
663 _MORE_PAGES_INDICATOR = 'yt-uix-load-more'
664 _MORE_PAGES_URL = 'http://www.youtube.com/channel_ajax?action_load_more_videos=1&flow=list&paging=%s&view=0&sort=da&channel_id=%s'
665 IE_NAME = u'youtube:channel'
667 def extract_videos_from_page(self, page):
669 for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&?', page):
670 if mobj.group(1) not in ids_in_page:
671 ids_in_page.append(mobj.group(1))
674 def _real_extract(self, url):
676 mobj = re.match(self._VALID_URL, url)
678 raise ExtractorError(u'Invalid URL: %s' % url)
680 # Download channel page
681 channel_id = mobj.group(1)
685 url = self._TEMPLATE_URL % (channel_id, pagenum)
686 page = self._download_webpage(url, channel_id,
687 u'Downloading page #%s' % pagenum)
689 # Extract video identifiers
690 ids_in_page = self.extract_videos_from_page(page)
691 video_ids.extend(ids_in_page)
693 # Download any subsequent channel pages using the json-based channel_ajax query
694 if self._MORE_PAGES_INDICATOR in page:
696 pagenum = pagenum + 1
698 url = self._MORE_PAGES_URL % (pagenum, channel_id)
699 page = self._download_webpage(url, channel_id,
700 u'Downloading page #%s' % pagenum)
702 page = json.loads(page)
704 ids_in_page = self.extract_videos_from_page(page['content_html'])
705 video_ids.extend(ids_in_page)
707 if self._MORE_PAGES_INDICATOR not in page['load_more_widget_html']:
710 self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
712 urls = ['http://www.youtube.com/watch?v=%s' % id for id in video_ids]
713 url_entries = [self.url_result(url, 'Youtube') for url in urls]
714 return [self.playlist_result(url_entries, channel_id)]
717 class YoutubeUserIE(InfoExtractor):
718 """Information Extractor for YouTube users."""
720 _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/user/)|ytuser:)([A-Za-z0-9_-]+)'
721 _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
722 _GDATA_PAGE_SIZE = 50
723 _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d'
724 _VIDEO_INDICATOR = r'/watch\?v=(.+?)[\<&]'
725 IE_NAME = u'youtube:user'
727 def _real_extract(self, url):
729 mobj = re.match(self._VALID_URL, url)
731 raise ExtractorError(u'Invalid URL: %s' % url)
733 username = mobj.group(1)
735 # Download video ids using YouTube Data API. Result size per
736 # query is limited (currently to 50 videos) so we need to query
737 # page by page until there are no video ids - it means we got
744 start_index = pagenum * self._GDATA_PAGE_SIZE + 1
746 gdata_url = self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index)
747 page = self._download_webpage(gdata_url, username,
748 u'Downloading video ids from %d to %d' % (start_index, start_index + self._GDATA_PAGE_SIZE))
750 # Extract video identifiers
753 for mobj in re.finditer(self._VIDEO_INDICATOR, page):
754 if mobj.group(1) not in ids_in_page:
755 ids_in_page.append(mobj.group(1))
757 video_ids.extend(ids_in_page)
759 # A little optimization - if current page is not
760 # "full", ie. does not contain PAGE_SIZE video ids then
761 # we can assume that this page is the last one - there
762 # are no more ids on further pages - no need to query
765 if len(ids_in_page) < self._GDATA_PAGE_SIZE:
770 urls = ['http://www.youtube.com/watch?v=%s' % video_id for video_id in video_ids]
771 url_results = [self.url_result(url, 'Youtube') for url in urls]
772 return [self.playlist_result(url_results, playlist_title = username)]
774 class YoutubeSearchIE(SearchInfoExtractor):
775 """Information Extractor for YouTube search queries."""
776 _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
778 IE_NAME = u'youtube:search'
779 _SEARCH_KEY = 'ytsearch'
781 def report_download_page(self, query, pagenum):
782 """Report attempt to download search page with given number."""
783 self._downloader.to_screen(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
785 def _get_n_results(self, query, n):
786 """Get a specified number of results for a query"""
792 while (50 * pagenum) < limit:
793 self.report_download_page(query, pagenum+1)
794 result_url = self._API_URL % (compat_urllib_parse.quote_plus(query), (50*pagenum)+1)
795 request = compat_urllib_request.Request(result_url)
797 data = compat_urllib_request.urlopen(request).read().decode('utf-8')
798 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
799 raise ExtractorError(u'Unable to download API page: %s' % compat_str(err))
800 api_response = json.loads(data)['data']
802 if not 'items' in api_response:
803 raise ExtractorError(u'[youtube] No video results')
805 new_ids = list(video['id'] for video in api_response['items'])
808 limit = min(n, api_response['totalItems'])
811 if len(video_ids) > n:
812 video_ids = video_ids[:n]
813 videos = [self.url_result('http://www.youtube.com/watch?v=%s' % id, 'Youtube') for id in video_ids]
814 return self.playlist_result(videos, query)