1 from __future__ import unicode_literals
8 from .common import InfoExtractor
15 get_element_by_attribute,
23 class InstagramIE(InfoExtractor):
24 _VALID_URL = r'(?P<url>https?://(?:www\.)?instagram\.com/p/(?P<id>[^/?#&]+))'
26 'url': 'https://instagram.com/p/aye83DjauH/?foo=bar#abc',
27 'md5': '0d2da106a9d2631273e192b372806516',
31 'title': 'Video by naomipq',
32 'description': 'md5:1f17f0ab29bd6fe2bfad705f58de3cb8',
33 'thumbnail': r're:^https?://.*\.jpg',
34 'timestamp': 1371748545,
35 'upload_date': '20130620',
36 'uploader_id': 'naomipq',
37 'uploader': 'Naomi Leonor Phan-Quang',
44 'url': 'https://www.instagram.com/p/BA-pQFBG8HZ/?taken-by=britneyspears',
48 'title': 'Video by britneyspears',
49 'thumbnail': r're:^https?://.*\.jpg',
50 'timestamp': 1453760977,
51 'upload_date': '20160125',
52 'uploader_id': 'britneyspears',
53 'uploader': 'Britney Spears',
59 'skip_download': True,
63 'url': 'https://www.instagram.com/p/BQ0eAlwhDrw/',
85 'title': 'Post by instagram',
86 'description': 'md5:0f9203fc6a2ce4d228da5754bcf54957',
89 'url': 'https://instagram.com/p/-Cmh1cukG2/',
90 'only_matching': True,
92 'url': 'http://instagram.com/p/9o6LshA7zy/embed/',
93 'only_matching': True,
97 def _extract_embed_url(webpage):
99 r'<iframe[^>]+src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?instagram\.com/p/[^/]+/embed.*?)\1',
102 return mobj.group('url')
104 blockquote_el = get_element_by_attribute(
105 'class', 'instagram-media', webpage)
106 if blockquote_el is None:
110 r'<a[^>]+href=([\'"])(?P<link>[^\'"]+)\1', blockquote_el)
112 return mobj.group('link')
114 def _real_extract(self, url):
115 mobj = re.match(self._VALID_URL, url)
116 video_id = mobj.group('id')
117 url = mobj.group('url')
119 webpage = self._download_webpage(url, video_id)
121 (video_url, description, thumbnail, timestamp, uploader,
122 uploader_id, like_count, comment_count, comments, height,
125 shared_data = self._parse_json(
127 r'window\._sharedData\s*=\s*({.+?});',
128 webpage, 'shared data', default='{}'),
129 video_id, fatal=False)
133 (lambda x: x['entry_data']['PostPage'][0]['graphql']['shortcode_media'],
134 lambda x: x['entry_data']['PostPage'][0]['media']),
137 video_url = media.get('video_url')
138 height = int_or_none(media.get('dimensions', {}).get('height'))
139 width = int_or_none(media.get('dimensions', {}).get('width'))
140 description = try_get(
141 media, lambda x: x['edge_media_to_caption']['edges'][0]['node']['text'],
142 compat_str) or media.get('caption')
143 thumbnail = media.get('display_src')
144 timestamp = int_or_none(media.get('taken_at_timestamp') or media.get('date'))
145 uploader = media.get('owner', {}).get('full_name')
146 uploader_id = media.get('owner', {}).get('username')
148 def get_count(key, kind):
149 return int_or_none(try_get(
150 media, (lambda x: x['edge_media_%s' % key]['count'],
151 lambda x: x['%ss' % kind]['count'])))
152 like_count = get_count('preview_like', 'like')
153 comment_count = get_count('to_comment', 'comment')
156 'author': comment.get('user', {}).get('username'),
157 'author_id': comment.get('user', {}).get('id'),
158 'id': comment.get('id'),
159 'text': comment.get('text'),
160 'timestamp': int_or_none(comment.get('created_at')),
161 } for comment in media.get(
162 'comments', {}).get('nodes', []) if comment.get('text')]
165 media, lambda x: x['edge_sidecar_to_children']['edges'],
169 for edge_num, edge in enumerate(edges, start=1):
170 node = try_get(edge, lambda x: x['node'], dict)
173 node_video_url = try_get(node, lambda x: x['video_url'], compat_str)
174 if not node_video_url:
177 'id': node.get('shortcode') or node['id'],
178 'title': 'Video %d' % edge_num,
179 'url': node_video_url,
180 'thumbnail': node.get('display_url'),
181 'width': int_or_none(try_get(node, lambda x: x['dimensions']['width'])),
182 'height': int_or_none(try_get(node, lambda x: x['dimensions']['height'])),
183 'view_count': int_or_none(node.get('video_view_count')),
185 return self.playlist_result(
187 'Post by %s' % uploader_id if uploader_id else None,
191 video_url = self._og_search_video_url(webpage, secure=False)
200 uploader_id = self._search_regex(
201 r'"owner"\s*:\s*{\s*"username"\s*:\s*"(.+?)"',
202 webpage, 'uploader id', fatal=False)
205 description = self._search_regex(
206 r'"caption"\s*:\s*"(.+?)"', webpage, 'description', default=None)
207 if description is not None:
208 description = lowercase_escape(description)
211 thumbnail = self._og_search_thumbnail(webpage)
217 'title': 'Video by %s' % uploader_id,
218 'description': description,
219 'thumbnail': thumbnail,
220 'timestamp': timestamp,
221 'uploader_id': uploader_id,
222 'uploader': uploader,
223 'like_count': like_count,
224 'comment_count': comment_count,
225 'comments': comments,
229 class InstagramUserIE(InfoExtractor):
230 _VALID_URL = r'https?://(?:www\.)?instagram\.com/(?P<id>[^/]{2,})/?(?:$|[?#])'
231 IE_DESC = 'Instagram user profile'
232 IE_NAME = 'instagram:user'
234 'url': 'https://instagram.com/porsche',
241 'extract_flat': True,
242 'skip_download': True,
249 def _entries(self, data):
250 def get_count(suffix):
251 return int_or_none(try_get(
252 node, lambda x: x['edge_media_' + suffix]['count']))
254 uploader_id = data['entry_data']['ProfilePage'][0]['graphql']['user']['id']
255 csrf_token = data['config']['csrf_token']
256 rhx_gis = data.get('rhx_gis') or '3c7ca9dcefcf966d11dacf1f151335e8'
258 self._set_cookie('instagram.com', 'ig_pr', '1')
261 for page_num in itertools.count(1):
262 variables = json.dumps({
269 gis_tmpls = [self._gis_tmpl]
274 '%s:%s' % (rhx_gis, csrf_token),
275 '%s:%s:%s' % (rhx_gis, csrf_token, std_headers['User-Agent']),
278 for gis_tmpl in gis_tmpls:
280 media = self._download_json(
281 'https://www.instagram.com/graphql/query/', uploader_id,
282 'Downloading JSON page %d' % page_num, headers={
283 'X-Requested-With': 'XMLHttpRequest',
284 'X-Instagram-GIS': hashlib.md5(
285 ('%s:%s' % (gis_tmpl, variables)).encode('utf-8')).hexdigest(),
287 'query_hash': '42323d64886122307be10013ad2dcc44',
288 'variables': variables,
289 })['data']['user']['edge_owner_to_timeline_media']
290 self._gis_tmpl = gis_tmpl
292 except ExtractorError as e:
293 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
294 if gis_tmpl != gis_tmpls[-1]:
298 edges = media.get('edges')
299 if not edges or not isinstance(edges, list):
303 node = edge.get('node')
304 if not node or not isinstance(node, dict):
306 if node.get('__typename') != 'GraphVideo' and node.get('is_video') is not True:
308 video_id = node.get('shortcode')
312 info = self.url_result(
313 'https://instagram.com/p/%s/' % video_id,
314 ie=InstagramIE.ie_key(), video_id=video_id)
316 description = try_get(
317 node, lambda x: x['edge_media_to_caption']['edges'][0]['node']['text'],
319 thumbnail = node.get('thumbnail_src') or node.get('display_src')
320 timestamp = int_or_none(node.get('taken_at_timestamp'))
322 comment_count = get_count('to_comment')
323 like_count = get_count('preview_like')
324 view_count = int_or_none(node.get('video_view_count'))
327 'description': description,
328 'thumbnail': thumbnail,
329 'timestamp': timestamp,
330 'comment_count': comment_count,
331 'like_count': like_count,
332 'view_count': view_count,
337 page_info = media.get('page_info')
338 if not page_info or not isinstance(page_info, dict):
341 has_next_page = page_info.get('has_next_page')
342 if not has_next_page:
345 cursor = page_info.get('end_cursor')
346 if not cursor or not isinstance(cursor, compat_str):
349 def _real_extract(self, url):
350 username = self._match_id(url)
352 webpage = self._download_webpage(url, username)
354 data = self._parse_json(
356 r'sharedData\s*=\s*({.+?})\s*;\s*[<\n]', webpage, 'data'),
359 return self.playlist_result(
360 self._entries(data), username, username)