1 from __future__ import unicode_literals
8 from .common import InfoExtractor
15 get_element_by_attribute,
24 class InstagramIE(InfoExtractor):
25 _VALID_URL = r'(?P<url>https?://(?:www\.)?instagram\.com/(?:p|tv|reel)/(?P<id>[^/?#&]+))'
27 'url': 'https://instagram.com/p/aye83DjauH/?foo=bar#abc',
28 'md5': '0d2da106a9d2631273e192b372806516',
32 'title': 'Video by naomipq',
33 'description': 'md5:1f17f0ab29bd6fe2bfad705f58de3cb8',
34 'thumbnail': r're:^https?://.*\.jpg',
35 'timestamp': 1371748545,
36 'upload_date': '20130620',
37 'uploader_id': 'naomipq',
38 'uploader': 'Naomi Leonor Phan-Quang',
45 'url': 'https://www.instagram.com/p/BA-pQFBG8HZ/?taken-by=britneyspears',
49 'title': 'Video by britneyspears',
50 'thumbnail': r're:^https?://.*\.jpg',
51 'timestamp': 1453760977,
52 'upload_date': '20160125',
53 'uploader_id': 'britneyspears',
54 'uploader': 'Britney Spears',
60 'skip_download': True,
64 'url': 'https://www.instagram.com/p/BQ0eAlwhDrw/',
86 'title': 'Post by instagram',
87 'description': 'md5:0f9203fc6a2ce4d228da5754bcf54957',
90 'url': 'https://instagram.com/p/-Cmh1cukG2/',
91 'only_matching': True,
93 'url': 'http://instagram.com/p/9o6LshA7zy/embed/',
94 'only_matching': True,
96 'url': 'https://www.instagram.com/tv/aye83DjauH/',
97 'only_matching': True,
99 'url': 'https://www.instagram.com/reel/CDUMkliABpa/',
100 'only_matching': True,
104 def _extract_embed_url(webpage):
106 r'<iframe[^>]+src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?instagram\.com/p/[^/]+/embed.*?)\1',
109 return mobj.group('url')
111 blockquote_el = get_element_by_attribute(
112 'class', 'instagram-media', webpage)
113 if blockquote_el is None:
117 r'<a[^>]+href=([\'"])(?P<link>[^\'"]+)\1', blockquote_el)
119 return mobj.group('link')
121 def _real_extract(self, url):
122 mobj = re.match(self._VALID_URL, url)
123 video_id = mobj.group('id')
124 url = mobj.group('url')
126 webpage = self._download_webpage(url, video_id)
128 (media, video_url, description, thumbnail, timestamp, uploader,
129 uploader_id, like_count, comment_count, comments, height,
132 shared_data = self._parse_json(
134 r'window\._sharedData\s*=\s*({.+?});',
135 webpage, 'shared data', default='{}'),
136 video_id, fatal=False)
140 (lambda x: x['entry_data']['PostPage'][0]['graphql']['shortcode_media'],
141 lambda x: x['entry_data']['PostPage'][0]['media']),
143 # _sharedData.entry_data.PostPage is empty when authenticated (see
144 # https://github.com/ytdl-org/youtube-dl/pull/22880)
146 additional_data = self._parse_json(
148 r'window\.__additionalDataLoaded\s*\(\s*[^,]+,\s*({.+?})\s*\)\s*;',
149 webpage, 'additional data', default='{}'),
150 video_id, fatal=False)
153 additional_data, lambda x: x['graphql']['shortcode_media'],
156 video_url = media.get('video_url')
157 height = int_or_none(media.get('dimensions', {}).get('height'))
158 width = int_or_none(media.get('dimensions', {}).get('width'))
159 description = try_get(
160 media, lambda x: x['edge_media_to_caption']['edges'][0]['node']['text'],
161 compat_str) or media.get('caption')
162 thumbnail = media.get('display_src') or media.get('display_url')
163 timestamp = int_or_none(media.get('taken_at_timestamp') or media.get('date'))
164 uploader = media.get('owner', {}).get('full_name')
165 uploader_id = media.get('owner', {}).get('username')
167 def get_count(key, kind):
168 return int_or_none(try_get(
169 media, (lambda x: x['edge_media_%s' % key]['count'],
170 lambda x: x['%ss' % kind]['count'])))
171 like_count = get_count('preview_like', 'like')
172 comment_count = get_count('to_comment', 'comment')
175 'author': comment.get('user', {}).get('username'),
176 'author_id': comment.get('user', {}).get('id'),
177 'id': comment.get('id'),
178 'text': comment.get('text'),
179 'timestamp': int_or_none(comment.get('created_at')),
180 } for comment in media.get(
181 'comments', {}).get('nodes', []) if comment.get('text')]
184 media, lambda x: x['edge_sidecar_to_children']['edges'],
188 for edge_num, edge in enumerate(edges, start=1):
189 node = try_get(edge, lambda x: x['node'], dict)
192 node_video_url = url_or_none(node.get('video_url'))
193 if not node_video_url:
196 'id': node.get('shortcode') or node['id'],
197 'title': 'Video %d' % edge_num,
198 'url': node_video_url,
199 'thumbnail': node.get('display_url'),
200 'width': int_or_none(try_get(node, lambda x: x['dimensions']['width'])),
201 'height': int_or_none(try_get(node, lambda x: x['dimensions']['height'])),
202 'view_count': int_or_none(node.get('video_view_count')),
204 return self.playlist_result(
206 'Post by %s' % uploader_id if uploader_id else None,
210 video_url = self._og_search_video_url(webpage, secure=False)
219 uploader_id = self._search_regex(
220 r'"owner"\s*:\s*{\s*"username"\s*:\s*"(.+?)"',
221 webpage, 'uploader id', fatal=False)
224 description = self._search_regex(
225 r'"caption"\s*:\s*"(.+?)"', webpage, 'description', default=None)
226 if description is not None:
227 description = lowercase_escape(description)
230 thumbnail = self._og_search_thumbnail(webpage)
236 'title': 'Video by %s' % uploader_id,
237 'description': description,
238 'thumbnail': thumbnail,
239 'timestamp': timestamp,
240 'uploader_id': uploader_id,
241 'uploader': uploader,
242 'like_count': like_count,
243 'comment_count': comment_count,
244 'comments': comments,
248 class InstagramPlaylistIE(InfoExtractor):
249 # A superclass for handling any kind of query based on GraphQL which
250 # results in a playlist.
252 _gis_tmpl = None # used to cache GIS request type
254 def _parse_graphql(self, webpage, item_id):
255 # Reads a webpage and returns its GraphQL data.
256 return self._parse_json(
258 r'sharedData\s*=\s*({.+?})\s*;\s*[<\n]', webpage, 'data'),
261 def _extract_graphql(self, data, url):
262 # Parses GraphQL queries containing videos and generates a playlist.
263 def get_count(suffix):
264 return int_or_none(try_get(
265 node, lambda x: x['edge_media_' + suffix]['count']))
267 uploader_id = self._match_id(url)
268 csrf_token = data['config']['csrf_token']
269 rhx_gis = data.get('rhx_gis') or '3c7ca9dcefcf966d11dacf1f151335e8'
272 for page_num in itertools.count(1):
277 variables.update(self._query_vars_for(data))
278 variables = json.dumps(variables)
281 gis_tmpls = [self._gis_tmpl]
286 '%s:%s' % (rhx_gis, csrf_token),
287 '%s:%s:%s' % (rhx_gis, csrf_token, std_headers['User-Agent']),
290 # try all of the ways to generate a GIS query, and not only use the
291 # first one that works, but cache it for future requests
292 for gis_tmpl in gis_tmpls:
294 json_data = self._download_json(
295 'https://www.instagram.com/graphql/query/', uploader_id,
296 'Downloading JSON page %d' % page_num, headers={
297 'X-Requested-With': 'XMLHttpRequest',
298 'X-Instagram-GIS': hashlib.md5(
299 ('%s:%s' % (gis_tmpl, variables)).encode('utf-8')).hexdigest(),
301 'query_hash': self._QUERY_HASH,
302 'variables': variables,
304 media = self._parse_timeline_from(json_data)
305 self._gis_tmpl = gis_tmpl
307 except ExtractorError as e:
308 # if it's an error caused by a bad query, and there are
309 # more GIS templates to try, ignore it and keep trying
310 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
311 if gis_tmpl != gis_tmpls[-1]:
315 edges = media.get('edges')
316 if not edges or not isinstance(edges, list):
320 node = edge.get('node')
321 if not node or not isinstance(node, dict):
323 if node.get('__typename') != 'GraphVideo' and node.get('is_video') is not True:
325 video_id = node.get('shortcode')
329 info = self.url_result(
330 'https://instagram.com/p/%s/' % video_id,
331 ie=InstagramIE.ie_key(), video_id=video_id)
333 description = try_get(
334 node, lambda x: x['edge_media_to_caption']['edges'][0]['node']['text'],
336 thumbnail = node.get('thumbnail_src') or node.get('display_src')
337 timestamp = int_or_none(node.get('taken_at_timestamp'))
339 comment_count = get_count('to_comment')
340 like_count = get_count('preview_like')
341 view_count = int_or_none(node.get('video_view_count'))
344 'description': description,
345 'thumbnail': thumbnail,
346 'timestamp': timestamp,
347 'comment_count': comment_count,
348 'like_count': like_count,
349 'view_count': view_count,
354 page_info = media.get('page_info')
355 if not page_info or not isinstance(page_info, dict):
358 has_next_page = page_info.get('has_next_page')
359 if not has_next_page:
362 cursor = page_info.get('end_cursor')
363 if not cursor or not isinstance(cursor, compat_str):
366 def _real_extract(self, url):
367 user_or_tag = self._match_id(url)
368 webpage = self._download_webpage(url, user_or_tag)
369 data = self._parse_graphql(webpage, user_or_tag)
371 self._set_cookie('instagram.com', 'ig_pr', '1')
373 return self.playlist_result(
374 self._extract_graphql(data, url), user_or_tag, user_or_tag)
377 class InstagramUserIE(InstagramPlaylistIE):
378 _VALID_URL = r'https?://(?:www\.)?instagram\.com/(?P<id>[^/]{2,})/?(?:$|[?#])'
379 IE_DESC = 'Instagram user profile'
380 IE_NAME = 'instagram:user'
382 'url': 'https://instagram.com/porsche',
389 'extract_flat': True,
390 'skip_download': True,
395 _QUERY_HASH = '42323d64886122307be10013ad2dcc44',
398 def _parse_timeline_from(data):
399 # extracts the media timeline data from a GraphQL result
400 return data['data']['user']['edge_owner_to_timeline_media']
403 def _query_vars_for(data):
404 # returns a dictionary of variables to add to the timeline query based
405 # on the GraphQL of the original page
407 'id': data['entry_data']['ProfilePage'][0]['graphql']['user']['id']
411 class InstagramTagIE(InstagramPlaylistIE):
412 _VALID_URL = r'https?://(?:www\.)?instagram\.com/explore/tags/(?P<id>[^/]+)'
413 IE_DESC = 'Instagram hashtag search'
414 IE_NAME = 'instagram:tag'
416 'url': 'https://instagram.com/explore/tags/lolcats',
421 'playlist_count': 50,
423 'extract_flat': True,
424 'skip_download': True,
429 _QUERY_HASH = 'f92f56d47dc7a55b606908374b43a314',
432 def _parse_timeline_from(data):
433 # extracts the media timeline data from a GraphQL result
434 return data['data']['hashtag']['edge_hashtag_to_media']
437 def _query_vars_for(data):
438 # returns a dictionary of variables to add to the timeline query based
439 # on the GraphQL of the original page
442 data['entry_data']['TagPage'][0]['graphql']['hashtag']['name']