9 from .common
import InfoExtractor
10 from ..compat
import (
17 get_element_by_attribute
,
29 class InstagramBaseIE(InfoExtractor
):
30 _NETRC_MACHINE
= 'instagram'
34 username
, password
= self
._get
_login
_info
()
35 if username
is None or self
._IS
_LOGGED
_IN
:
38 login_webpage
= self
._download
_webpage
(
39 'https://www.instagram.com/accounts/login/', None,
40 note
='Downloading login webpage', errnote
='Failed to download login webpage')
42 shared_data
= self
._parse
_json
(
44 r
'window\._sharedData\s*=\s*({.+?});',
45 login_webpage
, 'shared data', default
='{}'),
48 login
= self
._download
_json
('https://www.instagram.com/accounts/login/ajax/', None, note
='Logging in', headers
={
50 'X-IG-App-ID': '936619743392459',
51 'X-ASBD-ID': '198387',
52 'X-IG-WWW-Claim': '0',
53 'X-Requested-With': 'XMLHttpRequest',
54 'X-CSRFToken': shared_data
['config']['csrf_token'],
55 'X-Instagram-AJAX': shared_data
['rollout_hash'],
56 'Referer': 'https://www.instagram.com/',
57 }, data
=urlencode_postdata({
58 'enc_password': f
'#PWD_INSTAGRAM_BROWSER:0:{int(time.time())}:{password}',
61 'optIntoOneTap': 'false',
62 'stopDeletionNonce': '',
63 'trustedDeviceRecords': '{}',
66 if not login
.get('authenticated'):
67 if login
.get('message'):
68 raise ExtractorError(f
'Unable to login: {login["message"]}')
69 elif login
.get('user'):
70 raise ExtractorError('Unable to login: Sorry, your password was incorrect. Please double-check your password.', expected
=True)
71 elif login
.get('user') is False:
72 raise ExtractorError('Unable to login: The username you entered doesn\'t belong to an account. Please check your username and try again.', expected
=True)
73 raise ExtractorError('Unable to login')
74 InstagramBaseIE
._IS
_LOGGED
_IN
= True
76 def _real_initialize(self
):
79 def _get_count(self
, media
, kind
, *keys
):
81 media
, (kind
, 'count'), *((f
'edge_media_{key}', 'count') for key
in keys
),
82 expected_type
=int_or_none
)
84 def _get_dimension(self
, name
, media
, webpage
=None):
86 traverse_obj(media
, ('dimensions', name
), expected_type
=int_or_none
)
87 or int_or_none(self
._html
_search
_meta
(
88 (f
'og:video:{name}', f
'video:{name}'), webpage
or '', default
=None)))
90 def _extract_nodes(self
, nodes
, is_direct
=False):
91 for idx
, node
in enumerate(nodes
, start
=1):
92 if node
.get('__typename') != 'GraphVideo' and node
.get('is_video') is not True:
95 video_id
= node
.get('shortcode')
99 'id': video_id
or node
['id'],
100 'url': node
.get('video_url'),
101 'width': self
._get
_dimension
('width', node
),
102 'height': self
._get
_dimension
('height', node
),
104 'Referer': 'https://www.instagram.com/',
112 'ie_key': 'Instagram',
114 'url': f
'https://instagram.com/p/{video_id}',
119 'title': node
.get('title') or (f
'Video {idx}' if is_direct
else None),
120 'description': traverse_obj(
121 node
, ('edge_media_to_caption', 'edges', 0, 'node', 'text'), expected_type
=str),
122 'thumbnail': traverse_obj(
123 node
, 'display_url', 'thumbnail_src', 'display_src', expected_type
=url_or_none
),
124 'duration': float_or_none(node
.get('video_duration')),
125 'timestamp': int_or_none(node
.get('taken_at_timestamp')),
126 'view_count': int_or_none(node
.get('video_view_count')),
127 'comment_count': self
._get
_count
(node
, 'comments', 'preview_comment', 'to_comment', 'to_parent_comment'),
128 'like_count': self
._get
_count
(node
, 'likes', 'preview_like'),
131 def _extract_product_media(self
, product_media
):
132 media_id
= product_media
.get('code') or product_media
.get('id')
133 vcodec
= product_media
.get('video_codec')
134 dash_manifest_raw
= product_media
.get('video_dash_manifest')
135 videos_list
= product_media
.get('video_versions')
136 if not (dash_manifest_raw
or videos_list
):
140 'format_id': format
.get('id'),
141 'url': format
.get('url'),
142 'width': format
.get('width'),
143 'height': format
.get('height'),
145 } for format
in videos_list
or []]
146 if dash_manifest_raw
:
147 formats
.extend(self
._parse
_mpd
_formats
(self
._parse
_xml
(dash_manifest_raw
, media_id
), mpd_id
='dash'))
148 self
._sort
_formats
(formats
)
151 'url': thumbnail
.get('url'),
152 'width': thumbnail
.get('width'),
153 'height': thumbnail
.get('height')
154 } for thumbnail
in traverse_obj(product_media
, ('image_versions2', 'candidates')) or []]
157 'duration': float_or_none(product_media
.get('video_duration')),
159 'thumbnails': thumbnails
162 def _extract_product(self
, product_info
):
163 if isinstance(product_info
, list):
164 product_info
= product_info
[0]
166 user_info
= product_info
.get('user') or {}
168 'id': product_info
.get('code') or product_info
.get('id'),
169 'title': product_info
.get('title') or f
'Video by {user_info.get("username")}',
170 'description': traverse_obj(product_info
, ('caption', 'text'), expected_type
=str_or_none
),
171 'timestamp': int_or_none(product_info
.get('taken_at')),
172 'channel': user_info
.get('username'),
173 'uploader': user_info
.get('full_name'),
174 'uploader_id': str_or_none(user_info
.get('pk')),
175 'view_count': int_or_none(product_info
.get('view_count')),
176 'like_count': int_or_none(product_info
.get('like_count')),
177 'comment_count': int_or_none(product_info
.get('comment_count')),
179 'Referer': 'https://www.instagram.com/',
182 carousel_media
= product_info
.get('carousel_media')
187 'title': f
'Post by {user_info.get("username")}',
190 **self
._extract
_product
_media
(product_media
),
191 } for product_media
in carousel_media
],
196 **self
._extract
_product
_media
(product_info
)
200 class InstagramIOSIE(InfoExtractor
):
201 IE_DESC
= 'IOS instagram:// URL'
202 _VALID_URL
= r
'instagram://media\?id=(?P<id>[\d_]+)'
204 'url': 'instagram://media?id=482584233761418119',
205 'md5': '0d2da106a9d2631273e192b372806516',
209 'title': 'Video by naomipq',
210 'description': 'md5:1f17f0ab29bd6fe2bfad705f58de3cb8',
211 'thumbnail': r
're:^https?://.*\.jpg',
213 'timestamp': 1371748545,
214 'upload_date': '20130620',
215 'uploader_id': 'naomipq',
216 'uploader': 'B E A U T Y F O R A S H E S',
218 'comment_count': int,
221 'add_ie': ['Instagram']
224 def _get_id(self
, id):
225 """Source: https://stackoverflow.com/questions/24437823/getting-instagram-post-url-from-media-id"""
226 chrs
= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
227 media_id
= int(id.split('_')[0])
231 media_id
= (media_id
- r
) // 64
232 shortened_id
= chrs
[r
] + shortened_id
235 def _real_extract(self
, url
):
237 '_type': 'url_transparent',
238 'url': f
'http://instagram.com/tv/{self._get_id(self._match_id(url))}/',
239 'ie_key': 'Instagram',
243 class InstagramIE(InstagramBaseIE
):
244 _VALID_URL
= r
'(?P<url>https?://(?:www\.)?instagram\.com(?:/[^/]+)?/(?:p|tv|reel)/(?P<id>[^/?#&]+))'
246 'url': 'https://instagram.com/p/aye83DjauH/?foo=bar#abc',
247 'md5': '0d2da106a9d2631273e192b372806516',
251 'title': 'Video by naomipq',
252 'description': 'md5:1f17f0ab29bd6fe2bfad705f58de3cb8',
253 'thumbnail': r
're:^https?://.*\.jpg',
255 'timestamp': 1371748545,
256 'upload_date': '20130620',
257 'uploader_id': '2815873',
258 'uploader': 'B E A U T Y F O R A S H E S',
259 'channel': 'naomipq',
261 'comment_count': int,
265 # missing description
266 'url': 'https://www.instagram.com/p/BA-pQFBG8HZ/?taken-by=britneyspears',
270 'title': 'Video by britneyspears',
271 'thumbnail': r
're:^https?://.*\.jpg',
273 'timestamp': 1453760977,
274 'upload_date': '20160125',
275 'uploader_id': '12246775',
276 'uploader': 'Britney Spears',
277 'channel': 'britneyspears',
279 'comment_count': int,
283 'skip_download': True,
287 'url': 'https://www.instagram.com/p/BQ0eAlwhDrw/',
309 'title': 'Post by instagram',
310 'description': 'md5:0f9203fc6a2ce4d228da5754bcf54957',
314 'url': 'https://www.instagram.com/tv/BkfuX9UB-eK/',
318 'title': 'Fingerboarding Tricks with @cass.fb',
319 'thumbnail': r
're:^https?://.*\.jpg',
321 'timestamp': 1530032919,
322 'upload_date': '20180626',
323 'uploader_id': '25025320',
324 'uploader': 'Instagram',
325 'channel': 'instagram',
327 'comment_count': int,
329 'description': 'Meet Cass Hirst (@cass.fb), a fingerboarding pro who can perform tiny ollies and kickflips while blindfolded.',
332 'url': 'https://instagram.com/p/-Cmh1cukG2/',
333 'only_matching': True,
335 'url': 'http://instagram.com/p/9o6LshA7zy/embed/',
336 'only_matching': True,
338 'url': 'https://www.instagram.com/tv/aye83DjauH/',
339 'only_matching': True,
341 'url': 'https://www.instagram.com/reel/CDUMkliABpa/',
342 'only_matching': True,
344 'url': 'https://www.instagram.com/marvelskies.fc/reel/CWqAgUZgCku/',
345 'only_matching': True,
349 def _extract_embed_url(webpage
):
351 r
'<iframe[^>]+src=(["\'])(?P
<url
>(?
:https?
:)?
//(?
:www\
.)?instagram\
.com
/p
/[^
/]+/embed
.*?
)\
1',
354 return mobj.group('url
')
356 blockquote_el = get_element_by_attribute(
357 'class', 'instagram
-media
', webpage)
358 if blockquote_el is None:
362 r'<a
[^
>]+href
=([\'"])(?P<link>[^\'"]+)\
1', blockquote_el)
364 return mobj.group('link
')
366 def _real_extract(self, url):
367 video_id, url = self._match_valid_url(url).group('id', 'url
')
368 webpage, urlh = self._download_webpage_handle(url, video_id)
369 if 'www
.instagram
.com
/accounts
/login
' in urlh.geturl():
370 self.report_warning('Main webpage
is locked behind the login page
. '
371 'Retrying
with embed
webpage (Note that some metadata might be missing
)')
372 webpage = self._download_webpage(
373 'https
://www
.instagram
.com
/p
/%s/embed
/' % video_id, video_id, note='Downloading embed webpage
')
375 shared_data = self._parse_json(
377 r'window\
._sharedData\s
*=\s
*({.+?}
);',
378 webpage, 'shared data
', default='{}'),
379 video_id, fatal=False)
380 media = traverse_obj(
382 ('entry_data
', 'PostPage
', 0, 'graphql
', 'shortcode_media
'),
383 ('entry_data
', 'PostPage
', 0, 'media
'),
386 # _sharedData.entry_data.PostPage is empty when authenticated (see
387 # https://github.com/ytdl-org/youtube-dl/pull/22880)
389 additional_data = self._parse_json(
391 r'window\
.__additionalDataLoaded\s
*\
(\s
*[^
,]+,\s
*({.+?}
)\s
*\
);',
392 webpage, 'additional data
', default='{}'),
393 video_id, fatal=False)
394 product_item = traverse_obj(additional_data, ('items
', 0), expected_type=dict)
396 return self._extract_product(product_item)
397 media = traverse_obj(additional_data, ('graphql
', 'shortcode_media
'), 'shortcode_media
', expected_type=dict) or {}
399 if not media and 'www
.instagram
.com
/accounts
/login
' in urlh.geturl():
400 self.raise_login_required('You need to log
in to access this content
')
402 username = traverse_obj(media, ('owner
', 'username
')) or self._search_regex(
403 r'"owner"\s
*:\s
*{\s
*"username"\s
*:\s
*"(.+?)"', webpage, 'username
', fatal=False)
406 traverse_obj(media, ('edge_media_to_caption
', 'edges
', 0, 'node
', 'text
'), expected_type=str)
407 or media.get('caption
'))
409 description = self._search_regex(
410 r'"caption"\s
*:\s
*"(.+?)"', webpage, 'description
', default=None)
411 if description is not None:
412 description = lowercase_escape(description)
414 video_url = media.get('video_url
')
416 nodes = traverse_obj(media, ('edge_sidecar_to_children
', 'edges
', ..., 'node
'), expected_type=dict) or []
418 return self.playlist_result(
419 self._extract_nodes(nodes, True), video_id,
420 format_field(username, template='Post by
%s'), description)
422 video_url = self._og_search_video_url(webpage, secure=False)
426 'width
': self._get_dimension('width
', media, webpage),
427 'height
': self._get_dimension('height
', media, webpage),
429 dash = traverse_obj(media, ('dash_info
', 'video_dash_manifest
'))
431 formats.extend(self._parse_mpd_formats(self._parse_xml(dash, video_id), mpd_id='dash
'))
432 self._sort_formats(formats)
434 comment_data = traverse_obj(media, ('edge_media_to_parent_comment
', 'edges
'))
436 'author
': traverse_obj(comment_dict, ('node
', 'owner
', 'username
')),
437 'author_id
': traverse_obj(comment_dict, ('node
', 'owner
', 'id')),
438 'id': traverse_obj(comment_dict, ('node
', 'id')),
439 'text
': traverse_obj(comment_dict, ('node
', 'text
')),
440 'timestamp
': traverse_obj(comment_dict, ('node
', 'created_at
'), expected_type=int_or_none),
441 } for comment_dict in comment_data] if comment_data else None
443 display_resources = (
444 media.get('display_resources
')
445 or [{'src': media.get(key)} for key in ('display_src
', 'display_url
')]
446 or [{'src': self._og_search_thumbnail(webpage)}])
448 'url
': thumbnail['src
'],
449 'width
': thumbnail.get('config_width
'),
450 'height
': thumbnail.get('config_height
'),
451 } for thumbnail in display_resources if thumbnail.get('src
')]
456 'title
': media.get('title
') or 'Video by
%s' % username,
457 'description
': description,
458 'duration
': float_or_none(media.get('video_duration
')),
459 'timestamp
': traverse_obj(media, 'taken_at_timestamp
', 'date
', expected_type=int_or_none),
460 'uploader_id
': traverse_obj(media, ('owner
', 'id')),
461 'uploader
': traverse_obj(media, ('owner
', 'full_name
')),
463 'like_count
': self._get_count(media, 'likes
', 'preview_like
') or str_to_int(self._search_regex(
464 r'data
-log
-event
="likeCountClick"[^
>]*>[^\d
]*([\d
,\
.]+)', webpage, 'like count
', fatal=False)),
465 'comment_count
': self._get_count(media, 'comments
', 'preview_comment
', 'to_comment
', 'to_parent_comment
'),
466 'comments
': comments,
467 'thumbnails
': thumbnails,
469 'Referer
': 'https
://www
.instagram
.com
/',
474 class InstagramPlaylistBaseIE(InstagramBaseIE):
475 _gis_tmpl = None # used to cache GIS request type
477 def _parse_graphql(self, webpage, item_id):
478 # Reads a webpage and returns its GraphQL data.
479 return self._parse_json(
481 r'sharedData\s
*=\s
*({.+?}
)\s
*;\s
*[<\n]', webpage, 'data
'),
484 def _extract_graphql(self, data, url):
485 # Parses GraphQL queries containing videos and generates a playlist.
486 uploader_id = self._match_id(url)
487 csrf_token = data['config
']['csrf_token
']
488 rhx_gis = data.get('rhx_gis
') or '3c7ca9dcefcf966d11dacf1f151335e8
'
491 for page_num in itertools.count(1):
496 variables.update(self._query_vars_for(data))
497 variables = json.dumps(variables)
500 gis_tmpls = [self._gis_tmpl]
505 '%s:%s' % (rhx_gis, csrf_token),
506 '%s:%s:%s' % (rhx_gis, csrf_token, std_headers['User
-Agent
']),
509 # try all of the ways to generate a GIS query, and not only use the
510 # first one that works, but cache it for future requests
511 for gis_tmpl in gis_tmpls:
513 json_data = self._download_json(
514 'https
://www
.instagram
.com
/graphql
/query
/', uploader_id,
515 'Downloading JSON page
%d' % page_num, headers={
516 'X
-Requested
-With
': 'XMLHttpRequest
',
517 'X
-Instagram
-GIS
': hashlib.md5(
518 ('%s:%s' % (gis_tmpl, variables)).encode('utf
-8')).hexdigest(),
520 'query_hash
': self._QUERY_HASH,
521 'variables
': variables,
523 media = self._parse_timeline_from(json_data)
524 self._gis_tmpl = gis_tmpl
526 except ExtractorError as e:
527 # if it's an error caused by a bad query
, and there are
528 # more GIS templates to try, ignore it and keep trying
529 if isinstance(e
.cause
, compat_HTTPError
) and e
.cause
.code
== 403:
530 if gis_tmpl
!= gis_tmpls
[-1]:
534 nodes
= traverse_obj(media
, ('edges', ..., 'node'), expected_type
=dict) or []
537 yield from self
._extract
_nodes
(nodes
)
539 has_next_page
= traverse_obj(media
, ('page_info', 'has_next_page'))
540 cursor
= traverse_obj(media
, ('page_info', 'end_cursor'), expected_type
=str)
541 if not has_next_page
or not cursor
:
544 def _real_extract(self
, url
):
545 user_or_tag
= self
._match
_id
(url
)
546 webpage
= self
._download
_webpage
(url
, user_or_tag
)
547 data
= self
._parse
_graphql
(webpage
, user_or_tag
)
549 self
._set
_cookie
('instagram.com', 'ig_pr', '1')
551 return self
.playlist_result(
552 self
._extract
_graphql
(data
, url
), user_or_tag
, user_or_tag
)
555 class InstagramUserIE(InstagramPlaylistBaseIE
):
556 _VALID_URL
= r
'https?://(?:www\.)?instagram\.com/(?P<id>[^/]{2,})/?(?:$|[?#])'
557 IE_DESC
= 'Instagram user profile'
558 IE_NAME
= 'instagram:user'
560 'url': 'https://instagram.com/porsche',
567 'extract_flat': True,
568 'skip_download': True,
573 _QUERY_HASH
= '42323d64886122307be10013ad2dcc44',
576 def _parse_timeline_from(data
):
577 # extracts the media timeline data from a GraphQL result
578 return data
['data']['user']['edge_owner_to_timeline_media']
581 def _query_vars_for(data
):
582 # returns a dictionary of variables to add to the timeline query based
583 # on the GraphQL of the original page
585 'id': data
['entry_data']['ProfilePage'][0]['graphql']['user']['id']
589 class InstagramTagIE(InstagramPlaylistBaseIE
):
590 _VALID_URL
= r
'https?://(?:www\.)?instagram\.com/explore/tags/(?P<id>[^/]+)'
591 IE_DESC
= 'Instagram hashtag search URLs'
592 IE_NAME
= 'instagram:tag'
594 'url': 'https://instagram.com/explore/tags/lolcats',
599 'playlist_count': 50,
601 'extract_flat': True,
602 'skip_download': True,
607 _QUERY_HASH
= 'f92f56d47dc7a55b606908374b43a314',
610 def _parse_timeline_from(data
):
611 # extracts the media timeline data from a GraphQL result
612 return data
['data']['hashtag']['edge_hashtag_to_media']
615 def _query_vars_for(data
):
616 # returns a dictionary of variables to add to the timeline query based
617 # on the GraphQL of the original page
620 data
['entry_data']['TagPage'][0]['graphql']['hashtag']['name']
624 class InstagramStoryIE(InstagramBaseIE
):
625 _VALID_URL
= r
'https?://(?:www\.)?instagram\.com/stories/(?P<user>[^/]+)/(?P<id>\d+)'
626 IE_NAME
= 'instagram:story'
629 'url': 'https://www.instagram.com/stories/highlights/18090946048123978/',
631 'id': '18090946048123978',
634 'playlist_mincount': 50
637 def _real_extract(self
, url
):
638 username
, story_id
= self
._match
_valid
_url
(url
).groups()
640 story_info_url
= f
'{username}/{story_id}/?__a=1' if username
== 'highlights' else f
'{username}/?__a=1'
641 story_info
= self
._download
_json
(f
'https://www.instagram.com/stories/{story_info_url}', story_id
, headers
={
642 'X-IG-App-ID': 936619743392459,
645 'X-Requested-With': 'XMLHttpRequest',
648 user_id
= story_info
['user']['id']
649 highlight_title
= traverse_obj(story_info
, ('highlight', 'title'))
651 story_info_url
= user_id
if username
!= 'highlights' else f
'highlight:{story_id}'
652 videos
= self
._download
_json
(f
'https://i.instagram.com/api/v1/feed/reels_media/?reel_ids={story_info_url}', story_id
, headers
={
653 'X-IG-App-ID': 936619743392459,
658 full_name
= traverse_obj(videos
, ('user', 'full_name'))
661 if not (username
and username
!= 'highlights' and full_name
):
662 user_info
= self
._download
_json
(
663 f
'https://i.instagram.com/api/v1/users/{user_id}/info/', story_id
, headers
={
664 'User-Agent': 'Mozilla/5.0 (Linux; Android 11; SM-A505F Build/RP1A.200720.012; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/96.0.4664.45 Mobile Safari/537.36 Instagram 214.1.0.29.120 Android (30/11; 450dpi; 1080x2122; samsung; SM-A505F; a50; exynos9610; en_US; 333717274)',
665 }, note
='Downloading user info')
667 username
= traverse_obj(user_info
, ('user', 'username')) or username
668 full_name
= traverse_obj(user_info
, ('user', 'full_name')) or full_name
670 highlights
= traverse_obj(videos
, (f
'highlight:{story_id}', 'items'), (str(user_id
), 'items'))
671 return self
.playlist_result([{
672 **self
._extract
_product
(highlight
),
673 'title': f
'Story by {username}',
674 'uploader': full_name
,
675 'uploader_id': user_id
,
676 } for highlight
in highlights
], playlist_id
=story_id
, playlist_title
=highlight_title
)