9 from .common
import InfoExtractor
10 from ..compat
import (
17 get_element_by_attribute
,
28 class InstagramBaseIE(InfoExtractor
):
29 _NETRC_MACHINE
= 'instagram'
33 username
, password
= self
._get
_login
_info
()
34 if username
is None or self
._IS
_LOGGED
_IN
:
37 login_webpage
= self
._download
_webpage
(
38 'https://www.instagram.com/accounts/login/', None,
39 note
='Downloading login webpage', errnote
='Failed to download login webpage')
41 shared_data
= self
._parse
_json
(
43 r
'window\._sharedData\s*=\s*({.+?});',
44 login_webpage
, 'shared data', default
='{}'),
47 login
= self
._download
_json
('https://www.instagram.com/accounts/login/ajax/', None, note
='Logging in', headers
={
49 'X-IG-App-ID': '936619743392459',
50 'X-ASBD-ID': '198387',
51 'X-IG-WWW-Claim': '0',
52 'X-Requested-With': 'XMLHttpRequest',
53 'X-CSRFToken': shared_data
['config']['csrf_token'],
54 'X-Instagram-AJAX': shared_data
['rollout_hash'],
55 'Referer': 'https://www.instagram.com/',
56 }, data
=urlencode_postdata({
57 'enc_password': f
'#PWD_INSTAGRAM_BROWSER:0:{int(time.time())}:{password}',
60 'optIntoOneTap': 'false',
61 'stopDeletionNonce': '',
62 'trustedDeviceRecords': '{}',
65 if not login
.get('authenticated'):
66 if login
.get('message'):
67 raise ExtractorError(f
'Unable to login: {login["message"]}')
68 elif login
.get('user'):
69 raise ExtractorError('Unable to login: Sorry, your password was incorrect. Please double-check your password.', expected
=True)
70 elif login
.get('user') is False:
71 raise ExtractorError('Unable to login: The username you entered doesn\'t belong to an account. Please check your username and try again.', expected
=True)
72 raise ExtractorError('Unable to login')
73 InstagramBaseIE
._IS
_LOGGED
_IN
= True
75 def _real_initialize(self
):
78 def _get_count(self
, media
, kind
, *keys
):
80 media
, (kind
, 'count'), *((f
'edge_media_{key}', 'count') for key
in keys
),
81 expected_type
=int_or_none
)
83 def _get_dimension(self
, name
, media
, webpage
=None):
85 traverse_obj(media
, ('dimensions', name
), expected_type
=int_or_none
)
86 or int_or_none(self
._html
_search
_meta
(
87 (f
'og:video:{name}', f
'video:{name}'), webpage
or '', default
=None)))
89 def _extract_nodes(self
, nodes
, is_direct
=False):
90 for idx
, node
in enumerate(nodes
, start
=1):
91 if node
.get('__typename') != 'GraphVideo' and node
.get('is_video') is not True:
94 video_id
= node
.get('shortcode')
98 'id': video_id
or node
['id'],
99 'url': node
.get('video_url'),
100 'width': self
._get
_dimension
('width', node
),
101 'height': self
._get
_dimension
('height', node
),
103 'Referer': 'https://www.instagram.com/',
111 'ie_key': 'Instagram',
113 'url': f
'https://instagram.com/p/{video_id}',
118 'title': node
.get('title') or (f
'Video {idx}' if is_direct
else None),
119 'description': traverse_obj(
120 node
, ('edge_media_to_caption', 'edges', 0, 'node', 'text'), expected_type
=str),
121 'thumbnail': traverse_obj(
122 node
, 'display_url', 'thumbnail_src', 'display_src', expected_type
=url_or_none
),
123 'duration': float_or_none(node
.get('video_duration')),
124 'timestamp': int_or_none(node
.get('taken_at_timestamp')),
125 'view_count': int_or_none(node
.get('video_view_count')),
126 'comment_count': self
._get
_count
(node
, 'comments', 'preview_comment', 'to_comment', 'to_parent_comment'),
127 'like_count': self
._get
_count
(node
, 'likes', 'preview_like'),
130 def _extract_product_media(self
, product_media
):
131 media_id
= product_media
.get('code') or product_media
.get('id')
132 vcodec
= product_media
.get('video_codec')
133 dash_manifest_raw
= product_media
.get('video_dash_manifest')
134 videos_list
= product_media
.get('video_versions')
135 if not (dash_manifest_raw
or videos_list
):
139 'format_id': format
.get('id'),
140 'url': format
.get('url'),
141 'width': format
.get('width'),
142 'height': format
.get('height'),
144 } for format
in videos_list
or []]
145 if dash_manifest_raw
:
146 formats
.extend(self
._parse
_mpd
_formats
(self
._parse
_xml
(dash_manifest_raw
, media_id
), mpd_id
='dash'))
147 self
._sort
_formats
(formats
)
150 'url': thumbnail
.get('url'),
151 'width': thumbnail
.get('width'),
152 'height': thumbnail
.get('height')
153 } for thumbnail
in traverse_obj(product_media
, ('image_versions2', 'candidates')) or []]
156 'duration': float_or_none(product_media
.get('video_duration')),
158 'thumbnails': thumbnails
161 def _extract_product(self
, product_info
):
162 if isinstance(product_info
, list):
163 product_info
= product_info
[0]
165 user_info
= product_info
.get('user') or {}
167 'id': product_info
.get('code') or product_info
.get('id'),
168 'title': product_info
.get('title') or f
'Video by {user_info.get("username")}',
169 'description': traverse_obj(product_info
, ('caption', 'text'), expected_type
=str_or_none
),
170 'timestamp': int_or_none(product_info
.get('taken_at')),
171 'channel': user_info
.get('username'),
172 'uploader': user_info
.get('full_name'),
173 'uploader_id': str_or_none(user_info
.get('pk')),
174 'view_count': int_or_none(product_info
.get('view_count')),
175 'like_count': int_or_none(product_info
.get('like_count')),
176 'comment_count': int_or_none(product_info
.get('comment_count')),
178 'Referer': 'https://www.instagram.com/',
181 carousel_media
= product_info
.get('carousel_media')
186 'title': f
'Post by {user_info.get("username")}',
189 **self
._extract
_product
_media
(product_media
),
190 } for product_media
in carousel_media
],
195 **self
._extract
_product
_media
(product_info
)
199 class InstagramIOSIE(InfoExtractor
):
200 IE_DESC
= 'IOS instagram:// URL'
201 _VALID_URL
= r
'instagram://media\?id=(?P<id>[\d_]+)'
203 'url': 'instagram://media?id=482584233761418119',
204 'md5': '0d2da106a9d2631273e192b372806516',
208 'title': 'Video by naomipq',
209 'description': 'md5:1f17f0ab29bd6fe2bfad705f58de3cb8',
210 'thumbnail': r
're:^https?://.*\.jpg',
212 'timestamp': 1371748545,
213 'upload_date': '20130620',
214 'uploader_id': 'naomipq',
215 'uploader': 'B E A U T Y F O R A S H E S',
217 'comment_count': int,
220 'add_ie': ['Instagram']
223 def _get_id(self
, id):
224 """Source: https://stackoverflow.com/questions/24437823/getting-instagram-post-url-from-media-id"""
225 chrs
= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
226 media_id
= int(id.split('_')[0])
230 media_id
= (media_id
- r
) // 64
231 shortened_id
= chrs
[r
] + shortened_id
234 def _real_extract(self
, url
):
236 '_type': 'url_transparent',
237 'url': f
'http://instagram.com/tv/{self._get_id(self._match_id(url))}/',
238 'ie_key': 'Instagram',
242 class InstagramIE(InstagramBaseIE
):
243 _VALID_URL
= r
'(?P<url>https?://(?:www\.)?instagram\.com(?:/[^/]+)?/(?:p|tv|reel)/(?P<id>[^/?#&]+))'
245 'url': 'https://instagram.com/p/aye83DjauH/?foo=bar#abc',
246 'md5': '0d2da106a9d2631273e192b372806516',
250 'title': 'Video by naomipq',
251 'description': 'md5:1f17f0ab29bd6fe2bfad705f58de3cb8',
252 'thumbnail': r
're:^https?://.*\.jpg',
254 'timestamp': 1371748545,
255 'upload_date': '20130620',
256 'uploader_id': '2815873',
257 'uploader': 'B E A U T Y F O R A S H E S',
258 'channel': 'naomipq',
260 'comment_count': int,
264 # missing description
265 'url': 'https://www.instagram.com/p/BA-pQFBG8HZ/?taken-by=britneyspears',
269 'title': 'Video by britneyspears',
270 'thumbnail': r
're:^https?://.*\.jpg',
272 'timestamp': 1453760977,
273 'upload_date': '20160125',
274 'uploader_id': '12246775',
275 'uploader': 'Britney Spears',
276 'channel': 'britneyspears',
278 'comment_count': int,
282 'skip_download': True,
286 'url': 'https://www.instagram.com/p/BQ0eAlwhDrw/',
308 'title': 'Post by instagram',
309 'description': 'md5:0f9203fc6a2ce4d228da5754bcf54957',
313 'url': 'https://www.instagram.com/tv/BkfuX9UB-eK/',
317 'title': 'Fingerboarding Tricks with @cass.fb',
318 'thumbnail': r
're:^https?://.*\.jpg',
320 'timestamp': 1530032919,
321 'upload_date': '20180626',
322 'uploader_id': '25025320',
323 'uploader': 'Instagram',
324 'channel': 'instagram',
326 'comment_count': int,
328 'description': 'Meet Cass Hirst (@cass.fb), a fingerboarding pro who can perform tiny ollies and kickflips while blindfolded.',
331 'url': 'https://instagram.com/p/-Cmh1cukG2/',
332 'only_matching': True,
334 'url': 'http://instagram.com/p/9o6LshA7zy/embed/',
335 'only_matching': True,
337 'url': 'https://www.instagram.com/tv/aye83DjauH/',
338 'only_matching': True,
340 'url': 'https://www.instagram.com/reel/CDUMkliABpa/',
341 'only_matching': True,
343 'url': 'https://www.instagram.com/marvelskies.fc/reel/CWqAgUZgCku/',
344 'only_matching': True,
348 def _extract_embed_url(webpage
):
350 r
'<iframe[^>]+src=(["\'])(?P
<url
>(?
:https?
:)?
//(?
:www\
.)?instagram\
.com
/p
/[^
/]+/embed
.*?
)\
1',
353 return mobj.group('url
')
355 blockquote_el = get_element_by_attribute(
356 'class', 'instagram
-media
', webpage)
357 if blockquote_el is None:
361 r'<a
[^
>]+href
=([\'"])(?P<link>[^\'"]+)\
1', blockquote_el)
363 return mobj.group('link
')
365 def _real_extract(self, url):
366 video_id, url = self._match_valid_url(url).group('id', 'url
')
367 webpage, urlh = self._download_webpage_handle(url, video_id)
368 if 'www
.instagram
.com
/accounts
/login
' in urlh.geturl():
369 self.report_warning('Main webpage
is locked behind the login page
. '
370 'Retrying
with embed
webpage (Note that some metadata might be missing
)')
371 webpage = self._download_webpage(
372 'https
://www
.instagram
.com
/p
/%s/embed
/' % video_id, video_id, note='Downloading embed webpage
')
374 shared_data = self._parse_json(
376 r'window\
._sharedData\s
*=\s
*({.+?}
);',
377 webpage, 'shared data
', default='{}'),
378 video_id, fatal=False)
379 media = traverse_obj(
381 ('entry_data
', 'PostPage
', 0, 'graphql
', 'shortcode_media
'),
382 ('entry_data
', 'PostPage
', 0, 'media
'),
385 # _sharedData.entry_data.PostPage is empty when authenticated (see
386 # https://github.com/ytdl-org/youtube-dl/pull/22880)
388 additional_data = self._parse_json(
390 r'window\
.__additionalDataLoaded\s
*\
(\s
*[^
,]+,\s
*({.+?}
)\s
*\
);',
391 webpage, 'additional data
', default='{}'),
392 video_id, fatal=False)
393 product_item = traverse_obj(additional_data, ('items
', 0), expected_type=dict)
395 return self._extract_product(product_item)
396 media = traverse_obj(additional_data, ('graphql
', 'shortcode_media
'), 'shortcode_media
', expected_type=dict) or {}
398 if not media and 'www
.instagram
.com
/accounts
/login
' in urlh.geturl():
399 self.raise_login_required('You need to log
in to access this content
')
401 username = traverse_obj(media, ('owner
', 'username
')) or self._search_regex(
402 r'"owner"\s
*:\s
*{\s
*"username"\s
*:\s
*"(.+?)"', webpage, 'username
', fatal=False)
405 traverse_obj(media, ('edge_media_to_caption
', 'edges
', 0, 'node
', 'text
'), expected_type=str)
406 or media.get('caption
'))
408 description = self._search_regex(
409 r'"caption"\s
*:\s
*"(.+?)"', webpage, 'description
', default=None)
410 if description is not None:
411 description = lowercase_escape(description)
413 video_url = media.get('video_url
')
415 nodes = traverse_obj(media, ('edge_sidecar_to_children
', 'edges
', ..., 'node
'), expected_type=dict) or []
417 return self.playlist_result(
418 self._extract_nodes(nodes, True), video_id,
419 format_field(username, template='Post by
%s'), description)
421 video_url = self._og_search_video_url(webpage, secure=False)
425 'width
': self._get_dimension('width
', media, webpage),
426 'height
': self._get_dimension('height
', media, webpage),
428 dash = traverse_obj(media, ('dash_info
', 'video_dash_manifest
'))
430 formats.extend(self._parse_mpd_formats(self._parse_xml(dash, video_id), mpd_id='dash
'))
431 self._sort_formats(formats)
433 comment_data = traverse_obj(media, ('edge_media_to_parent_comment
', 'edges
'))
435 'author
': traverse_obj(comment_dict, ('node
', 'owner
', 'username
')),
436 'author_id
': traverse_obj(comment_dict, ('node
', 'owner
', 'id')),
437 'id': traverse_obj(comment_dict, ('node
', 'id')),
438 'text
': traverse_obj(comment_dict, ('node
', 'text
')),
439 'timestamp
': traverse_obj(comment_dict, ('node
', 'created_at
'), expected_type=int_or_none),
440 } for comment_dict in comment_data] if comment_data else None
442 display_resources = (
443 media.get('display_resources
')
444 or [{'src': media.get(key)} for key in ('display_src
', 'display_url
')]
445 or [{'src': self._og_search_thumbnail(webpage)}])
447 'url
': thumbnail['src
'],
448 'width
': thumbnail.get('config_width
'),
449 'height
': thumbnail.get('config_height
'),
450 } for thumbnail in display_resources if thumbnail.get('src
')]
455 'title
': media.get('title
') or 'Video by
%s' % username,
456 'description
': description,
457 'duration
': float_or_none(media.get('video_duration
')),
458 'timestamp
': traverse_obj(media, 'taken_at_timestamp
', 'date
', expected_type=int_or_none),
459 'uploader_id
': traverse_obj(media, ('owner
', 'id')),
460 'uploader
': traverse_obj(media, ('owner
', 'full_name
')),
462 'like_count
': self._get_count(media, 'likes
', 'preview_like
') or str_to_int(self._search_regex(
463 r'data
-log
-event
="likeCountClick"[^
>]*>[^\d
]*([\d
,\
.]+)', webpage, 'like count
', fatal=False)),
464 'comment_count
': self._get_count(media, 'comments
', 'preview_comment
', 'to_comment
', 'to_parent_comment
'),
465 'comments
': comments,
466 'thumbnails
': thumbnails,
468 'Referer
': 'https
://www
.instagram
.com
/',
473 class InstagramPlaylistBaseIE(InstagramBaseIE):
474 _gis_tmpl = None # used to cache GIS request type
476 def _parse_graphql(self, webpage, item_id):
477 # Reads a webpage and returns its GraphQL data.
478 return self._parse_json(
480 r'sharedData\s
*=\s
*({.+?}
)\s
*;\s
*[<\n]', webpage, 'data
'),
483 def _extract_graphql(self, data, url):
484 # Parses GraphQL queries containing videos and generates a playlist.
485 uploader_id = self._match_id(url)
486 csrf_token = data['config
']['csrf_token
']
487 rhx_gis = data.get('rhx_gis
') or '3c7ca9dcefcf966d11dacf1f151335e8
'
490 for page_num in itertools.count(1):
495 variables.update(self._query_vars_for(data))
496 variables = json.dumps(variables)
499 gis_tmpls = [self._gis_tmpl]
504 '%s:%s' % (rhx_gis, csrf_token),
505 '%s:%s:%s' % (rhx_gis, csrf_token, self.get_param('http_headers
')['User
-Agent
']),
508 # try all of the ways to generate a GIS query, and not only use the
509 # first one that works, but cache it for future requests
510 for gis_tmpl in gis_tmpls:
512 json_data = self._download_json(
513 'https
://www
.instagram
.com
/graphql
/query
/', uploader_id,
514 'Downloading JSON page
%d' % page_num, headers={
515 'X
-Requested
-With
': 'XMLHttpRequest
',
516 'X
-Instagram
-GIS
': hashlib.md5(
517 ('%s:%s' % (gis_tmpl, variables)).encode('utf
-8')).hexdigest(),
519 'query_hash
': self._QUERY_HASH,
520 'variables
': variables,
522 media = self._parse_timeline_from(json_data)
523 self._gis_tmpl = gis_tmpl
525 except ExtractorError as e:
526 # if it's an error caused by a bad query
, and there are
527 # more GIS templates to try, ignore it and keep trying
528 if isinstance(e
.cause
, compat_HTTPError
) and e
.cause
.code
== 403:
529 if gis_tmpl
!= gis_tmpls
[-1]:
533 nodes
= traverse_obj(media
, ('edges', ..., 'node'), expected_type
=dict) or []
536 yield from self
._extract
_nodes
(nodes
)
538 has_next_page
= traverse_obj(media
, ('page_info', 'has_next_page'))
539 cursor
= traverse_obj(media
, ('page_info', 'end_cursor'), expected_type
=str)
540 if not has_next_page
or not cursor
:
543 def _real_extract(self
, url
):
544 user_or_tag
= self
._match
_id
(url
)
545 webpage
= self
._download
_webpage
(url
, user_or_tag
)
546 data
= self
._parse
_graphql
(webpage
, user_or_tag
)
548 self
._set
_cookie
('instagram.com', 'ig_pr', '1')
550 return self
.playlist_result(
551 self
._extract
_graphql
(data
, url
), user_or_tag
, user_or_tag
)
554 class InstagramUserIE(InstagramPlaylistBaseIE
):
555 _VALID_URL
= r
'https?://(?:www\.)?instagram\.com/(?P<id>[^/]{2,})/?(?:$|[?#])'
556 IE_DESC
= 'Instagram user profile'
557 IE_NAME
= 'instagram:user'
559 'url': 'https://instagram.com/porsche',
566 'extract_flat': True,
567 'skip_download': True,
572 _QUERY_HASH
= '42323d64886122307be10013ad2dcc44',
575 def _parse_timeline_from(data
):
576 # extracts the media timeline data from a GraphQL result
577 return data
['data']['user']['edge_owner_to_timeline_media']
580 def _query_vars_for(data
):
581 # returns a dictionary of variables to add to the timeline query based
582 # on the GraphQL of the original page
584 'id': data
['entry_data']['ProfilePage'][0]['graphql']['user']['id']
588 class InstagramTagIE(InstagramPlaylistBaseIE
):
589 _VALID_URL
= r
'https?://(?:www\.)?instagram\.com/explore/tags/(?P<id>[^/]+)'
590 IE_DESC
= 'Instagram hashtag search URLs'
591 IE_NAME
= 'instagram:tag'
593 'url': 'https://instagram.com/explore/tags/lolcats',
598 'playlist_count': 50,
600 'extract_flat': True,
601 'skip_download': True,
606 _QUERY_HASH
= 'f92f56d47dc7a55b606908374b43a314',
609 def _parse_timeline_from(data
):
610 # extracts the media timeline data from a GraphQL result
611 return data
['data']['hashtag']['edge_hashtag_to_media']
614 def _query_vars_for(data
):
615 # returns a dictionary of variables to add to the timeline query based
616 # on the GraphQL of the original page
619 data
['entry_data']['TagPage'][0]['graphql']['hashtag']['name']
623 class InstagramStoryIE(InstagramBaseIE
):
624 _VALID_URL
= r
'https?://(?:www\.)?instagram\.com/stories/(?P<user>[^/]+)/(?P<id>\d+)'
625 IE_NAME
= 'instagram:story'
628 'url': 'https://www.instagram.com/stories/highlights/18090946048123978/',
630 'id': '18090946048123978',
633 'playlist_mincount': 50
636 def _real_extract(self
, url
):
637 username
, story_id
= self
._match
_valid
_url
(url
).groups()
639 story_info_url
= f
'{username}/{story_id}/?__a=1' if username
== 'highlights' else f
'{username}/?__a=1'
640 story_info
= self
._download
_json
(f
'https://www.instagram.com/stories/{story_info_url}', story_id
, headers
={
641 'X-IG-App-ID': 936619743392459,
644 'X-Requested-With': 'XMLHttpRequest',
647 user_id
= story_info
['user']['id']
648 highlight_title
= traverse_obj(story_info
, ('highlight', 'title'))
650 story_info_url
= user_id
if username
!= 'highlights' else f
'highlight:{story_id}'
651 videos
= self
._download
_json
(f
'https://i.instagram.com/api/v1/feed/reels_media/?reel_ids={story_info_url}', story_id
, headers
={
652 'X-IG-App-ID': 936619743392459,
657 full_name
= traverse_obj(videos
, ('user', 'full_name'))
660 if not (username
and username
!= 'highlights' and full_name
):
661 user_info
= self
._download
_json
(
662 f
'https://i.instagram.com/api/v1/users/{user_id}/info/', story_id
, headers
={
663 '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)',
664 }, note
='Downloading user info')
666 username
= traverse_obj(user_info
, ('user', 'username')) or username
667 full_name
= traverse_obj(user_info
, ('user', 'full_name')) or full_name
669 highlights
= traverse_obj(videos
, (f
'highlight:{story_id}', 'items'), (str(user_id
), 'items'))
670 return self
.playlist_result([{
671 **self
._extract
_product
(highlight
),
672 'title': f
'Story by {username}',
673 'uploader': full_name
,
674 'uploader_id': user_id
,
675 } for highlight
in highlights
], playlist_id
=story_id
, playlist_title
=highlight_title
)