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)/(?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,
101 def _extract_embed_url(webpage
):
103 r
'<iframe[^>]+src=(["\'])(?P
<url
>(?
:https?
:)?
//(?
:www\
.)?instagram\
.com
/p
/[^
/]+/embed
.*?
)\
1',
106 return mobj.group('url
')
108 blockquote_el = get_element_by_attribute(
109 'class', 'instagram
-media
', webpage)
110 if blockquote_el is None:
114 r'<a
[^
>]+href
=([\'"])(?P<link>[^\'"]+)\
1', blockquote_el)
116 return mobj.group('link
')
118 def _real_extract(self, url):
119 mobj = re.match(self._VALID_URL, url)
120 video_id = mobj.group('id')
121 url = mobj.group('url
')
123 webpage = self._download_webpage(url, video_id)
125 (video_url, description, thumbnail, timestamp, uploader,
126 uploader_id, like_count, comment_count, comments, height,
129 shared_data = self._parse_json(
131 r'window\
._sharedData\s
*=\s
*({.+?}
);',
132 webpage, 'shared data
', default='{}'),
133 video_id, fatal=False)
137 (lambda x: x['entry_data
']['PostPage
'][0]['graphql
']['shortcode_media
'],
138 lambda x: x['entry_data
']['PostPage
'][0]['media
']),
141 video_url = media.get('video_url
')
142 height = int_or_none(media.get('dimensions
', {}).get('height
'))
143 width = int_or_none(media.get('dimensions
', {}).get('width
'))
144 description = try_get(
145 media, lambda x: x['edge_media_to_caption
']['edges
'][0]['node
']['text
'],
146 compat_str) or media.get('caption
')
147 thumbnail = media.get('display_src
')
148 timestamp = int_or_none(media.get('taken_at_timestamp
') or media.get('date
'))
149 uploader = media.get('owner
', {}).get('full_name
')
150 uploader_id = media.get('owner
', {}).get('username
')
152 def get_count(key, kind):
153 return int_or_none(try_get(
154 media, (lambda x: x['edge_media_
%s' % key]['count
'],
155 lambda x: x['%ss' % kind]['count
'])))
156 like_count = get_count('preview_like
', 'like
')
157 comment_count = get_count('to_comment
', 'comment
')
160 'author
': comment.get('user
', {}).get('username
'),
161 'author_id
': comment.get('user
', {}).get('id'),
162 'id': comment.get('id'),
163 'text
': comment.get('text
'),
164 'timestamp
': int_or_none(comment.get('created_at
')),
165 } for comment in media.get(
166 'comments
', {}).get('nodes
', []) if comment.get('text
')]
169 media, lambda x: x['edge_sidecar_to_children
']['edges
'],
173 for edge_num, edge in enumerate(edges, start=1):
174 node = try_get(edge, lambda x: x['node
'], dict)
177 node_video_url = url_or_none(node.get('video_url
'))
178 if not node_video_url:
181 'id': node.get('shortcode
') or node['id'],
182 'title
': 'Video
%d' % edge_num,
183 'url
': node_video_url,
184 'thumbnail
': node.get('display_url
'),
185 'width
': int_or_none(try_get(node, lambda x: x['dimensions
']['width
'])),
186 'height
': int_or_none(try_get(node, lambda x: x['dimensions
']['height
'])),
187 'view_count
': int_or_none(node.get('video_view_count
')),
189 return self.playlist_result(
191 'Post by
%s' % uploader_id if uploader_id else None,
195 video_url = self._og_search_video_url(webpage, secure=False)
204 uploader_id = self._search_regex(
205 r'"owner"\s
*:\s
*{\s
*"username"\s
*:\s
*"(.+?)"',
206 webpage, 'uploader
id', fatal=False)
209 description = self._search_regex(
210 r'"caption"\s
*:\s
*"(.+?)"', webpage, 'description
', default=None)
211 if description is not None:
212 description = lowercase_escape(description)
215 thumbnail = self._og_search_thumbnail(webpage)
221 'title
': 'Video by
%s' % uploader_id,
222 'description
': description,
223 'thumbnail
': thumbnail,
224 'timestamp
': timestamp,
225 'uploader_id
': uploader_id,
226 'uploader
': uploader,
227 'like_count
': like_count,
228 'comment_count
': comment_count,
229 'comments
': comments,
233 class InstagramPlaylistIE(InfoExtractor):
234 # A superclass for handling any kind of query based on GraphQL which
235 # results in a playlist.
237 _gis_tmpl = None # used to cache GIS request type
239 def _parse_graphql(self, webpage, item_id):
240 # Reads a webpage and returns its GraphQL data.
241 return self._parse_json(
243 r'sharedData\s
*=\s
*({.+?}
)\s
*;\s
*[<\n]', webpage, 'data
'),
246 def _extract_graphql(self, data, url):
247 # Parses GraphQL queries containing videos and generates a playlist.
248 def get_count(suffix):
249 return int_or_none(try_get(
250 node, lambda x: x['edge_media_
' + suffix]['count
']))
252 uploader_id = self._match_id(url)
253 csrf_token = data['config
']['csrf_token
']
254 rhx_gis = data.get('rhx_gis
') or '3c7ca9dcefcf966d11dacf1f151335e8
'
257 for page_num in itertools.count(1):
262 variables.update(self._query_vars_for(data))
263 variables = json.dumps(variables)
266 gis_tmpls = [self._gis_tmpl]
271 '%s:%s' % (rhx_gis, csrf_token),
272 '%s:%s:%s' % (rhx_gis, csrf_token, std_headers['User
-Agent
']),
275 # try all of the ways to generate a GIS query, and not only use the
276 # first one that works, but cache it for future requests
277 for gis_tmpl in gis_tmpls:
279 json_data = self._download_json(
280 'https
://www
.instagram
.com
/graphql
/query
/', uploader_id,
281 'Downloading JSON page
%d' % page_num, headers={
282 'X
-Requested
-With
': 'XMLHttpRequest
',
283 'X
-Instagram
-GIS
': hashlib.md5(
284 ('%s:%s' % (gis_tmpl, variables)).encode('utf
-8')).hexdigest(),
286 'query_hash
': self._QUERY_HASH,
287 'variables
': variables,
289 media = self._parse_timeline_from(json_data)
290 self._gis_tmpl = gis_tmpl
292 except ExtractorError as e:
293 # if it's an error caused by a bad query
, and there are
294 # more GIS templates to try, ignore it and keep trying
295 if isinstance(e
.cause
, compat_HTTPError
) and e
.cause
.code
== 403:
296 if gis_tmpl
!= gis_tmpls
[-1]:
300 edges
= media
.get('edges')
301 if not edges
or not isinstance(edges
, list):
305 node
= edge
.get('node')
306 if not node
or not isinstance(node
, dict):
308 if node
.get('__typename') != 'GraphVideo' and node
.get('is_video') is not True:
310 video_id
= node
.get('shortcode')
314 info
= self
.url_result(
315 'https://instagram.com/p/%s/' % video_id
,
316 ie
=InstagramIE
.ie_key(), video_id
=video_id
)
318 description
= try_get(
319 node
, lambda x
: x
['edge_media_to_caption']['edges'][0]['node']['text'],
321 thumbnail
= node
.get('thumbnail_src') or node
.get('display_src')
322 timestamp
= int_or_none(node
.get('taken_at_timestamp'))
324 comment_count
= get_count('to_comment')
325 like_count
= get_count('preview_like')
326 view_count
= int_or_none(node
.get('video_view_count'))
329 'description': description
,
330 'thumbnail': thumbnail
,
331 'timestamp': timestamp
,
332 'comment_count': comment_count
,
333 'like_count': like_count
,
334 'view_count': view_count
,
339 page_info
= media
.get('page_info')
340 if not page_info
or not isinstance(page_info
, dict):
343 has_next_page
= page_info
.get('has_next_page')
344 if not has_next_page
:
347 cursor
= page_info
.get('end_cursor')
348 if not cursor
or not isinstance(cursor
, compat_str
):
351 def _real_extract(self
, url
):
352 user_or_tag
= self
._match
_id
(url
)
353 webpage
= self
._download
_webpage
(url
, user_or_tag
)
354 data
= self
._parse
_graphql
(webpage
, user_or_tag
)
356 self
._set
_cookie
('instagram.com', 'ig_pr', '1')
358 return self
.playlist_result(
359 self
._extract
_graphql
(data
, url
), user_or_tag
, user_or_tag
)
362 class InstagramUserIE(InstagramPlaylistIE
):
363 _VALID_URL
= r
'https?://(?:www\.)?instagram\.com/(?P<id>[^/]{2,})/?(?:$|[?#])'
364 IE_DESC
= 'Instagram user profile'
365 IE_NAME
= 'instagram:user'
367 'url': 'https://instagram.com/porsche',
374 'extract_flat': True,
375 'skip_download': True,
380 _QUERY_HASH
= '42323d64886122307be10013ad2dcc44',
383 def _parse_timeline_from(data
):
384 # extracts the media timeline data from a GraphQL result
385 return data
['data']['user']['edge_owner_to_timeline_media']
388 def _query_vars_for(data
):
389 # returns a dictionary of variables to add to the timeline query based
390 # on the GraphQL of the original page
392 'id': data
['entry_data']['ProfilePage'][0]['graphql']['user']['id']
396 class InstagramTagIE(InstagramPlaylistIE
):
397 _VALID_URL
= r
'https?://(?:www\.)?instagram\.com/explore/tags/(?P<id>[^/]+)'
398 IE_DESC
= 'Instagram hashtag search'
399 IE_NAME
= 'instagram:tag'
401 'url': 'https://instagram.com/explore/tags/lolcats',
406 'playlist_count': 50,
408 'extract_flat': True,
409 'skip_download': True,
414 _QUERY_HASH
= 'f92f56d47dc7a55b606908374b43a314',
417 def _parse_timeline_from(data
):
418 # extracts the media timeline data from a GraphQL result
419 return data
['data']['hashtag']['edge_hashtag_to_media']
422 def _query_vars_for(data
):
423 # returns a dictionary of variables to add to the timeline query based
424 # on the GraphQL of the original page
427 data
['entry_data']['TagPage'][0]['graphql']['hashtag']['name']