7 from .common
import InfoExtractor
8 from ..networking
.exceptions
import HTTPError
16 get_element_by_attribute
,
26 _ENCODING_CHARS
= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
29 def _pk_to_id(media_id
):
30 """Source: https://stackoverflow.com/questions/24437823/getting-instagram-post-url-from-media-id"""
31 return encode_base_n(int(media_id
.split('_')[0]), table
=_ENCODING_CHARS
)
34 def _id_to_pk(shortcode
):
35 """Covert a shortcode to a numeric value"""
36 return decode_base_n(shortcode
[:11], table
=_ENCODING_CHARS
)
39 class InstagramBaseIE(InfoExtractor
):
40 _NETRC_MACHINE
= 'instagram'
43 _API_BASE_URL
= 'https://i.instagram.com/api/v1'
44 _LOGIN_URL
= 'https://www.instagram.com/accounts/login'
46 'X-IG-App-ID': '936619743392459',
47 'X-ASBD-ID': '198387',
48 'X-IG-WWW-Claim': '0',
49 'Origin': 'https://www.instagram.com',
53 def _perform_login(self
, username
, password
):
54 if self
._IS
_LOGGED
_IN
:
57 login_webpage
= self
._download
_webpage
(
58 self
._LOGIN
_URL
, None, note
='Downloading login webpage', errnote
='Failed to download login webpage')
60 shared_data
= self
._parse
_json
(self
._search
_regex
(
61 r
'window\._sharedData\s*=\s*({.+?});', login_webpage
, 'shared data', default
='{}'), None)
63 login
= self
._download
_json
(
64 f
'{self._LOGIN_URL}/ajax/', None, note
='Logging in', headers
={
66 'X-Requested-With': 'XMLHttpRequest',
67 'X-CSRFToken': shared_data
['config']['csrf_token'],
68 'X-Instagram-AJAX': shared_data
['rollout_hash'],
69 'Referer': 'https://www.instagram.com/',
70 }, data
=urlencode_postdata({
71 'enc_password': f
'#PWD_INSTAGRAM_BROWSER:0:{int(time.time())}:{password}',
74 'optIntoOneTap': 'false',
75 'stopDeletionNonce': '',
76 'trustedDeviceRecords': '{}',
79 if not login
.get('authenticated'):
80 if login
.get('message'):
81 raise ExtractorError(f
'Unable to login: {login["message"]}')
82 elif login
.get('user'):
83 raise ExtractorError('Unable to login: Sorry, your password was incorrect. Please double-check your password.', expected
=True)
84 elif login
.get('user') is False:
85 raise ExtractorError('Unable to login: The username you entered doesn\'t belong to an account. Please check your username and try again.', expected
=True)
86 raise ExtractorError('Unable to login')
87 InstagramBaseIE
._IS
_LOGGED
_IN
= True
89 def _get_count(self
, media
, kind
, *keys
):
91 media
, (kind
, 'count'), *((f
'edge_media_{key}', 'count') for key
in keys
),
92 expected_type
=int_or_none
)
94 def _get_dimension(self
, name
, media
, webpage
=None):
96 traverse_obj(media
, ('dimensions', name
), expected_type
=int_or_none
)
97 or int_or_none(self
._html
_search
_meta
(
98 (f
'og:video:{name}', f
'video:{name}'), webpage
or '', default
=None)))
100 def _extract_nodes(self
, nodes
, is_direct
=False):
101 for idx
, node
in enumerate(nodes
, start
=1):
102 if node
.get('__typename') != 'GraphVideo' and node
.get('is_video') is not True:
105 video_id
= node
.get('shortcode')
109 'id': video_id
or node
['id'],
110 'url': node
.get('video_url'),
111 'width': self
._get
_dimension
('width', node
),
112 'height': self
._get
_dimension
('height', node
),
114 'Referer': 'https://www.instagram.com/',
122 'ie_key': 'Instagram',
124 'url': f
'https://instagram.com/p/{video_id}',
129 'title': node
.get('title') or (f
'Video {idx}' if is_direct
else None),
130 'description': traverse_obj(
131 node
, ('edge_media_to_caption', 'edges', 0, 'node', 'text'), expected_type
=str),
132 'thumbnail': traverse_obj(
133 node
, 'display_url', 'thumbnail_src', 'display_src', expected_type
=url_or_none
),
134 'duration': float_or_none(node
.get('video_duration')),
135 'timestamp': int_or_none(node
.get('taken_at_timestamp')),
136 'view_count': int_or_none(node
.get('video_view_count')),
137 'comment_count': self
._get
_count
(node
, 'comments', 'preview_comment', 'to_comment', 'to_parent_comment'),
138 'like_count': self
._get
_count
(node
, 'likes', 'preview_like'),
141 def _extract_product_media(self
, product_media
):
142 media_id
= product_media
.get('code') or _pk_to_id(product_media
.get('pk'))
143 vcodec
= product_media
.get('video_codec')
144 dash_manifest_raw
= product_media
.get('video_dash_manifest')
145 videos_list
= product_media
.get('video_versions')
146 if not (dash_manifest_raw
or videos_list
):
150 'format_id': fmt
.get('id'),
151 'url': fmt
.get('url'),
152 'width': fmt
.get('width'),
153 'height': fmt
.get('height'),
155 } for fmt
in videos_list
or []]
156 if dash_manifest_raw
:
157 formats
.extend(self
._parse
_mpd
_formats
(self
._parse
_xml
(dash_manifest_raw
, media_id
), mpd_id
='dash'))
160 'url': thumbnail
.get('url'),
161 'width': thumbnail
.get('width'),
162 'height': thumbnail
.get('height'),
163 } for thumbnail
in traverse_obj(product_media
, ('image_versions2', 'candidates')) or []]
166 'duration': float_or_none(product_media
.get('video_duration')),
168 'thumbnails': thumbnails
,
171 def _extract_product(self
, product_info
):
172 if isinstance(product_info
, list):
173 product_info
= product_info
[0]
175 user_info
= product_info
.get('user') or {}
177 'id': _pk_to_id(traverse_obj(product_info
, 'pk', 'id', expected_type
=str_or_none
)[:19]),
178 'title': product_info
.get('title') or f
'Video by {user_info.get("username")}',
179 'description': traverse_obj(product_info
, ('caption', 'text'), expected_type
=str_or_none
),
180 'timestamp': int_or_none(product_info
.get('taken_at')),
181 'channel': user_info
.get('username'),
182 'uploader': user_info
.get('full_name'),
183 'uploader_id': str_or_none(user_info
.get('pk')),
184 'view_count': int_or_none(product_info
.get('view_count')),
185 'like_count': int_or_none(product_info
.get('like_count')),
186 'comment_count': int_or_none(product_info
.get('comment_count')),
187 '__post_extractor': self
.extract_comments(_pk_to_id(product_info
.get('pk'))),
189 'Referer': 'https://www.instagram.com/',
192 carousel_media
= product_info
.get('carousel_media')
197 'title': f
'Post by {user_info.get("username")}',
200 **self
._extract
_product
_media
(product_media
),
201 } for product_media
in carousel_media
],
206 **self
._extract
_product
_media
(product_info
),
209 def _get_comments(self
, video_id
):
210 comments_info
= self
._download
_json
(
211 f
'{self._API_BASE_URL}/media/{_id_to_pk(video_id)}/comments/?can_support_threading=true&permalink_enabled=false', video_id
,
212 fatal
=False, errnote
='Comments extraction failed', note
='Downloading comments info', headers
=self
._API
_HEADERS
) or {}
214 comment_data
= traverse_obj(comments_info
, ('edge_media_to_parent_comment', 'edges'), 'comments')
215 for comment_dict
in comment_data
or []:
217 'author': traverse_obj(comment_dict
, ('node', 'owner', 'username'), ('user', 'username')),
218 'author_id': traverse_obj(comment_dict
, ('node', 'owner', 'id'), ('user', 'pk')),
219 'author_thumbnail': traverse_obj(comment_dict
, ('node', 'owner', 'profile_pic_url'), ('user', 'profile_pic_url'), expected_type
=url_or_none
),
220 'id': traverse_obj(comment_dict
, ('node', 'id'), 'pk'),
221 'text': traverse_obj(comment_dict
, ('node', 'text'), 'text'),
222 'like_count': traverse_obj(comment_dict
, ('node', 'edge_liked_by', 'count'), 'comment_like_count', expected_type
=int_or_none
),
223 'timestamp': traverse_obj(comment_dict
, ('node', 'created_at'), 'created_at', expected_type
=int_or_none
),
227 class InstagramIOSIE(InfoExtractor
):
228 IE_DESC
= 'IOS instagram:// URL'
229 _VALID_URL
= r
'instagram://media\?id=(?P<id>[\d_]+)'
231 'url': 'instagram://media?id=482584233761418119',
232 'md5': '0d2da106a9d2631273e192b372806516',
236 'title': 'Video by naomipq',
237 'description': 'md5:1f17f0ab29bd6fe2bfad705f58de3cb8',
238 'thumbnail': r
're:^https?://.*\.jpg',
240 'timestamp': 1371748545,
241 'upload_date': '20130620',
242 'uploader_id': 'naomipq',
243 'uploader': 'B E A U T Y F O R A S H E S',
245 'comment_count': int,
248 'add_ie': ['Instagram'],
251 def _real_extract(self
, url
):
252 video_id
= _pk_to_id(self
._match
_id
(url
))
253 return self
.url_result(f
'http://instagram.com/tv/{video_id}', InstagramIE
, video_id
)
256 class InstagramIE(InstagramBaseIE
):
257 _VALID_URL
= r
'(?P<url>https?://(?:www\.)?instagram\.com(?:/[^/]+)?/(?:p|tv|reels?(?!/audio/))/(?P<id>[^/?#&]+))'
258 _EMBED_REGEX
= [r
'<iframe[^>]+src=(["\'])(?P
<url
>(?
:https?
:)?
//(?
:www\
.)?instagram\
.com
/p
/[^
/]+/embed
.*?
)\
1']
260 'url
': 'https
://instagram
.com
/p
/aye83DjauH
/?foo
=bar
#abc',
261 'md5': '0d2da106a9d2631273e192b372806516',
265 'title': 'Video by naomipq',
266 'description': 'md5:1f17f0ab29bd6fe2bfad705f58de3cb8',
267 'thumbnail': r
're:^https?://.*\.jpg',
269 'timestamp': 1371748545,
270 'upload_date': '20130620',
271 'uploader_id': '2815873',
272 'uploader': 'B E A U T Y F O R A S H E S',
273 'channel': 'naomipq',
275 'comment_count': int,
278 'expected_warnings': [
279 'General metadata extraction failed',
280 'Main webpage is locked behind the login page',
284 'url': 'https://www.instagram.com/reel/Chunk8-jurw/',
285 'md5': 'f6d8277f74515fa3ff9f5791426e42b1',
289 'title': 'Video by instagram',
290 'description': 'md5:c9cde483606ed6f80fbe9283a6a2b290',
291 'thumbnail': r
're:^https?://.*\.jpg',
293 'timestamp': 1661529231,
294 'upload_date': '20220826',
295 'uploader_id': '25025320',
296 'uploader': 'Instagram',
297 'channel': 'instagram',
299 'comment_count': int,
302 'expected_warnings': [
303 'General metadata extraction failed',
304 'Main webpage is locked behind the login page',
308 'url': 'https://www.instagram.com/p/BQ0eAlwhDrw/',
314 'thumbnail': r
're:^https?://.*\.jpg',
322 'thumbnail': r
're:^https?://.*\.jpg',
330 'thumbnail': r
're:^https?://.*\.jpg',
336 'title': 'Post by instagram',
337 'description': 'md5:0f9203fc6a2ce4d228da5754bcf54957',
339 'expected_warnings': [
340 'General metadata extraction failed',
341 'Main webpage is locked behind the login page',
345 'url': 'https://www.instagram.com/tv/BkfuX9UB-eK/',
349 'title': 'Fingerboarding Tricks with @cass.fb',
350 'thumbnail': r
're:^https?://.*\.jpg',
352 'timestamp': 1530032919,
353 'upload_date': '20180626',
354 'uploader_id': '25025320',
355 'uploader': 'Instagram',
356 'channel': 'instagram',
358 'comment_count': int,
360 'description': 'Meet Cass Hirst (@cass.fb), a fingerboarding pro who can perform tiny ollies and kickflips while blindfolded.',
362 'expected_warnings': [
363 'General metadata extraction failed',
364 'Main webpage is locked behind the login page',
367 'url': 'https://instagram.com/p/-Cmh1cukG2/',
368 'only_matching': True,
370 'url': 'http://instagram.com/p/9o6LshA7zy/embed/',
371 'only_matching': True,
373 'url': 'https://www.instagram.com/tv/aye83DjauH/',
374 'only_matching': True,
376 'url': 'https://www.instagram.com/reel/CDUMkliABpa/',
377 'only_matching': True,
379 'url': 'https://www.instagram.com/marvelskies.fc/reel/CWqAgUZgCku/',
380 'only_matching': True,
382 'url': 'https://www.instagram.com/reels/Cop84x6u7CP/',
383 'only_matching': True,
387 def _extract_embed_urls(cls
, url
, webpage
):
388 res
= tuple(super()._extract
_embed
_urls
(url
, webpage
))
392 mobj
= re
.search(r
'<a[^>]+href=([\'"])(?P<link>[^\'"]+)\
1',
393 get_element_by_attribute('class', 'instagram
-media
', webpage) or '')
395 return [mobj.group('link
')]
397 def _real_extract(self, url):
398 video_id, url = self._match_valid_url(url).group('id', 'url
')
399 media, webpage = {}, ''
401 if self._get_cookies(url).get('sessionid
'):
402 info = traverse_obj(self._download_json(
403 f'{self
._API
_BASE
_URL
}/media
/{_id_to_pk(video_id
)}/info
/', video_id,
404 fatal=False, errnote='Video info extraction failed
',
405 note='Downloading video info
', headers=self._API_HEADERS), ('items
', 0))
408 return self._extract_product(media)
410 api_check = self._download_json(
411 f'{self
._API
_BASE
_URL
}/web
/get_ruling_for_content
/?content_type
=MEDIA
&target_id
={_id_to_pk(video_id
)}',
412 video_id, headers=self._API_HEADERS, fatal=False, note='Setting up session
', errnote=False) or {}
413 csrf_token = self._get_cookies('https
://www
.instagram
.com
').get('csrftoken
')
416 self.report_warning('No csrf token
set by Instagram API
', video_id)
418 csrf_token = csrf_token.value if api_check.get('status
') == 'ok
' else None
420 self.report_warning('Instagram API
is not granting access
', video_id)
423 'shortcode
': video_id,
424 'child_comment_count
': 3,
425 'fetch_comment_count
': 40,
426 'parent_comment_count
': 24,
427 'has_threaded_comments
': True,
429 general_info = self._download_json(
430 'https
://www
.instagram
.com
/graphql
/query
/', video_id, fatal=False, errnote=False,
433 'X
-CSRFToken
': csrf_token or '',
434 'X
-Requested
-With
': 'XMLHttpRequest
',
437 'doc_id
': '8845758582119845',
438 'variables
': json.dumps(variables, separators=(',', ':')),
440 media.update(traverse_obj(general_info, ('data
', 'xdt_shortcode_media
')) or {})
443 self.report_warning('General metadata extraction
failed (some metadata might be missing
).', video_id)
444 webpage, urlh = self._download_webpage_handle(url, video_id)
445 shared_data = self._search_json(
446 r'window\
._sharedData\s
*=', webpage, 'shared data
', video_id, fatal=False) or {}
448 if shared_data and self._LOGIN_URL not in urlh.url:
449 media.update(traverse_obj(
450 shared_data, ('entry_data
', 'PostPage
', 0, 'graphql
', 'shortcode_media
'),
451 ('entry_data
', 'PostPage
', 0, 'media
'), expected_type=dict) or {})
453 self.report_warning('Main webpage
is locked behind the login page
. Retrying with embed
webpage (some metadata might be missing
).')
454 webpage = self._download_webpage(
455 f'{url}
/embed
/', video_id, note='Downloading embed webpage
', fatal=False) or ''
456 additional_data = self._search_json(
457 r'window\
.__additionalDataLoaded\s
*\
(\s
*[^
,]+,', webpage, 'additional data
', video_id, fatal=False)
458 if not additional_data and not media:
459 self.raise_login_required('Requested content
is not available
, rate
-limit reached
or login required
')
461 product_item = traverse_obj(additional_data, ('items
', 0), expected_type=dict)
463 media.update(product_item)
464 return self._extract_product(media)
466 media.update(traverse_obj(
467 additional_data, ('graphql
', 'shortcode_media
'), 'shortcode_media
', expected_type=dict) or {})
469 username = traverse_obj(media, ('owner
', 'username
')) or self._search_regex(
470 r'"owner"\s
*:\s
*{\s
*"username"\s
*:\s
*"(.+?)"', webpage, 'username
', fatal=False)
473 traverse_obj(media, ('edge_media_to_caption
', 'edges
', 0, 'node
', 'text
'), expected_type=str)
474 or media.get('caption
'))
476 description = self._search_regex(
477 r'"caption"\s
*:\s
*"(.+?)"', webpage, 'description
', default=None)
478 if description is not None:
479 description = lowercase_escape(description)
481 video_url = media.get('video_url
')
483 nodes = traverse_obj(media, ('edge_sidecar_to_children
', 'edges
', ..., 'node
'), expected_type=dict) or []
485 return self.playlist_result(
486 self._extract_nodes(nodes, True), video_id,
487 format_field(username, None, 'Post by
%s'), description)
489 video_url = self._og_search_video_url(webpage, secure=False)
493 'width
': self._get_dimension('width
', media, webpage),
494 'height
': self._get_dimension('height
', media, webpage),
496 dash = traverse_obj(media, ('dash_info
', 'video_dash_manifest
'))
498 formats.extend(self._parse_mpd_formats(self._parse_xml(dash, video_id), mpd_id='dash
'))
500 comment_data = traverse_obj(media, ('edge_media_to_parent_comment
', 'edges
'))
502 'author
': traverse_obj(comment_dict, ('node
', 'owner
', 'username
')),
503 'author_id
': traverse_obj(comment_dict, ('node
', 'owner
', 'id')),
504 'id': traverse_obj(comment_dict, ('node
', 'id')),
505 'text
': traverse_obj(comment_dict, ('node
', 'text
')),
506 'timestamp
': traverse_obj(comment_dict, ('node
', 'created_at
'), expected_type=int_or_none),
507 } for comment_dict in comment_data] if comment_data else None
509 display_resources = (
510 media.get('display_resources
')
511 or [{'src
': media.get(key)} for key in ('display_src
', 'display_url
')]
512 or [{'src
': self._og_search_thumbnail(webpage)}])
514 'url
': thumbnail['src
'],
515 'width
': thumbnail.get('config_width
'),
516 'height
': thumbnail.get('config_height
'),
517 } for thumbnail in display_resources if thumbnail.get('src
')]
522 'title
': media.get('title
') or f'Video by {username}
',
523 'description
': description,
524 'duration
': float_or_none(media.get('video_duration
')),
525 'timestamp
': traverse_obj(media, 'taken_at_timestamp
', 'date
', expected_type=int_or_none),
526 'uploader_id
': traverse_obj(media, ('owner
', 'id')),
527 'uploader
': traverse_obj(media, ('owner
', 'full_name
')),
529 'like_count
': self._get_count(media, 'likes
', 'preview_like
') or str_to_int(self._search_regex(
530 r'data
-log
-event
="likeCountClick"[^
>]*>[^\d
]*([\d
,\
.]+)', webpage, 'like count
', fatal=False)),
531 'comment_count
': self._get_count(media, 'comments
', 'preview_comment
', 'to_comment
', 'to_parent_comment
'),
532 'comments
': comments,
533 'thumbnails
': thumbnails,
535 'Referer
': 'https
://www
.instagram
.com
/',
540 class InstagramPlaylistBaseIE(InstagramBaseIE):
541 _gis_tmpl = None # used to cache GIS request type
543 def _parse_graphql(self, webpage, item_id):
544 # Reads a webpage and returns its GraphQL data.
545 return self._parse_json(
547 r'sharedData\s
*=\s
*({.+?
})\s
*;\s
*[<\n]', webpage, 'data
'),
550 def _extract_graphql(self, data, url):
551 # Parses GraphQL queries containing videos and generates a playlist.
552 uploader_id = self._match_id(url)
553 csrf_token = data['config
']['csrf_token
']
554 rhx_gis = data.get('rhx_gis
') or '3c7ca9dcefcf966d11dacf1f151335e8
'
557 for page_num in itertools.count(1):
562 variables.update(self._query_vars_for(data))
563 variables = json.dumps(variables)
566 gis_tmpls = [self._gis_tmpl]
571 f'{rhx_gis}
:{csrf_token}
',
572 '{}:{}:{}'.format(rhx_gis, csrf_token, self.get_param('http_headers
')['User
-Agent
']),
575 # try all of the ways to generate a GIS query, and not only use the
576 # first one that works, but cache it for future requests
577 for gis_tmpl in gis_tmpls:
579 json_data = self._download_json(
580 'https
://www
.instagram
.com
/graphql
/query
/', uploader_id,
581 f'Downloading JSON page {page_num}
', headers={
582 'X
-Requested
-With
': 'XMLHttpRequest
',
583 'X
-Instagram
-GIS
': hashlib.md5(
584 (f'{gis_tmpl}
:{variables}
').encode()).hexdigest(),
586 'query_hash
': self._QUERY_HASH,
587 'variables
': variables,
589 media = self._parse_timeline_from(json_data)
590 self._gis_tmpl = gis_tmpl
592 except ExtractorError as e:
593 # if it's an error caused by a bad query
, and there are
594 # more GIS templates to try, ignore it and keep trying
595 if isinstance(e
.cause
, HTTPError
) and e
.cause
.status
== 403:
596 if gis_tmpl
!= gis_tmpls
[-1]:
600 nodes
= traverse_obj(media
, ('edges', ..., 'node'), expected_type
=dict) or []
603 yield from self
._extract
_nodes
(nodes
)
605 has_next_page
= traverse_obj(media
, ('page_info', 'has_next_page'))
606 cursor
= traverse_obj(media
, ('page_info', 'end_cursor'), expected_type
=str)
607 if not has_next_page
or not cursor
:
610 def _real_extract(self
, url
):
611 user_or_tag
= self
._match
_id
(url
)
612 webpage
= self
._download
_webpage
(url
, user_or_tag
)
613 data
= self
._parse
_graphql
(webpage
, user_or_tag
)
615 self
._set
_cookie
('instagram.com', 'ig_pr', '1')
617 return self
.playlist_result(
618 self
._extract
_graphql
(data
, url
), user_or_tag
, user_or_tag
)
621 class InstagramUserIE(InstagramPlaylistBaseIE
):
623 _VALID_URL
= r
'https?://(?:www\.)?instagram\.com/(?P<id>[^/]{2,})/?(?:$|[?#])'
624 IE_DESC
= 'Instagram user profile'
625 IE_NAME
= 'instagram:user'
627 'url': 'https://instagram.com/porsche',
634 'extract_flat': True,
635 'skip_download': True,
640 _QUERY_HASH
= ('42323d64886122307be10013ad2dcc44',)
643 def _parse_timeline_from(data
):
644 # extracts the media timeline data from a GraphQL result
645 return data
['data']['user']['edge_owner_to_timeline_media']
648 def _query_vars_for(data
):
649 # returns a dictionary of variables to add to the timeline query based
650 # on the GraphQL of the original page
652 'id': data
['entry_data']['ProfilePage'][0]['graphql']['user']['id'],
656 class InstagramTagIE(InstagramPlaylistBaseIE
):
657 _VALID_URL
= r
'https?://(?:www\.)?instagram\.com/explore/tags/(?P<id>[^/]+)'
658 IE_DESC
= 'Instagram hashtag search URLs'
659 IE_NAME
= 'instagram:tag'
661 'url': 'https://instagram.com/explore/tags/lolcats',
666 'playlist_count': 50,
668 'extract_flat': True,
669 'skip_download': True,
674 _QUERY_HASH
= ('f92f56d47dc7a55b606908374b43a314',)
677 def _parse_timeline_from(data
):
678 # extracts the media timeline data from a GraphQL result
679 return data
['data']['hashtag']['edge_hashtag_to_media']
682 def _query_vars_for(data
):
683 # returns a dictionary of variables to add to the timeline query based
684 # on the GraphQL of the original page
687 data
['entry_data']['TagPage'][0]['graphql']['hashtag']['name'],
691 class InstagramStoryIE(InstagramBaseIE
):
692 _VALID_URL
= r
'https?://(?:www\.)?instagram\.com/stories/(?P<user>[^/]+)/(?P<id>\d+)'
693 IE_NAME
= 'instagram:story'
696 'url': 'https://www.instagram.com/stories/highlights/18090946048123978/',
698 'id': '18090946048123978',
701 'playlist_mincount': 50,
704 def _real_extract(self
, url
):
705 username
, story_id
= self
._match
_valid
_url
(url
).groups()
706 story_info
= self
._download
_webpage
(url
, story_id
)
707 user_info
= self
._search
_json
(r
'"user":', story_info
, 'user info', story_id
, fatal
=False)
709 self
.raise_login_required('This content is unreachable')
711 user_id
= traverse_obj(user_info
, 'pk', 'id', expected_type
=str)
712 story_info_url
= user_id
if username
!= 'highlights' else f
'highlight:{story_id}'
713 if not story_info_url
: # user id is only mandatory for non-highlights
714 raise ExtractorError('Unable to extract user id')
716 videos
= traverse_obj(self
._download
_json
(
717 f
'{self._API_BASE_URL}/feed/reels_media/?reel_ids={story_info_url}',
718 story_id
, errnote
=False, fatal
=False, headers
=self
._API
_HEADERS
), 'reels')
720 self
.raise_login_required('You need to log in to access this content')
722 full_name
= traverse_obj(videos
, (f
'highlight:{story_id}', 'user', 'full_name'), (user_id
, 'user', 'full_name'))
723 story_title
= traverse_obj(videos
, (f
'highlight:{story_id}', 'title'))
725 story_title
= f
'Story by {username}'
727 highlights
= traverse_obj(videos
, (f
'highlight:{story_id}', 'items'), (user_id
, 'items'))
729 for highlight
in highlights
:
730 highlight_data
= self
._extract
_product
(highlight
)
731 if highlight_data
.get('formats'):
733 'uploader': full_name
,
734 'uploader_id': user_id
,
735 **filter_dict(highlight_data
),
737 return self
.playlist_result(info_data
, playlist_id
=story_id
, playlist_title
=story_title
)