7 from .common
import InfoExtractor
15 get_element_by_attribute
,
26 class InstagramBaseIE(InfoExtractor
):
27 _NETRC_MACHINE
= 'instagram'
30 def _perform_login(self
, username
, password
):
31 if self
._IS
_LOGGED
_IN
:
34 login_webpage
= self
._download
_webpage
(
35 'https://www.instagram.com/accounts/login/', None,
36 note
='Downloading login webpage', errnote
='Failed to download login webpage')
38 shared_data
= self
._parse
_json
(
40 r
'window\._sharedData\s*=\s*({.+?});',
41 login_webpage
, 'shared data', default
='{}'),
44 login
= self
._download
_json
('https://www.instagram.com/accounts/login/ajax/', None, note
='Logging in', headers
={
46 'X-IG-App-ID': '936619743392459',
47 'X-ASBD-ID': '198387',
48 'X-IG-WWW-Claim': '0',
49 'X-Requested-With': 'XMLHttpRequest',
50 'X-CSRFToken': shared_data
['config']['csrf_token'],
51 'X-Instagram-AJAX': shared_data
['rollout_hash'],
52 'Referer': 'https://www.instagram.com/',
53 }, data
=urlencode_postdata({
54 'enc_password': f
'#PWD_INSTAGRAM_BROWSER:0:{int(time.time())}:{password}',
57 'optIntoOneTap': 'false',
58 'stopDeletionNonce': '',
59 'trustedDeviceRecords': '{}',
62 if not login
.get('authenticated'):
63 if login
.get('message'):
64 raise ExtractorError(f
'Unable to login: {login["message"]}')
65 elif login
.get('user'):
66 raise ExtractorError('Unable to login: Sorry, your password was incorrect. Please double-check your password.', expected
=True)
67 elif login
.get('user') is False:
68 raise ExtractorError('Unable to login: The username you entered doesn\'t belong to an account. Please check your username and try again.', expected
=True)
69 raise ExtractorError('Unable to login')
70 InstagramBaseIE
._IS
_LOGGED
_IN
= True
72 def _get_count(self
, media
, kind
, *keys
):
74 media
, (kind
, 'count'), *((f
'edge_media_{key}', 'count') for key
in keys
),
75 expected_type
=int_or_none
)
77 def _get_dimension(self
, name
, media
, webpage
=None):
79 traverse_obj(media
, ('dimensions', name
), expected_type
=int_or_none
)
80 or int_or_none(self
._html
_search
_meta
(
81 (f
'og:video:{name}', f
'video:{name}'), webpage
or '', default
=None)))
83 def _extract_nodes(self
, nodes
, is_direct
=False):
84 for idx
, node
in enumerate(nodes
, start
=1):
85 if node
.get('__typename') != 'GraphVideo' and node
.get('is_video') is not True:
88 video_id
= node
.get('shortcode')
92 'id': video_id
or node
['id'],
93 'url': node
.get('video_url'),
94 'width': self
._get
_dimension
('width', node
),
95 'height': self
._get
_dimension
('height', node
),
97 'Referer': 'https://www.instagram.com/',
105 'ie_key': 'Instagram',
107 'url': f
'https://instagram.com/p/{video_id}',
112 'title': node
.get('title') or (f
'Video {idx}' if is_direct
else None),
113 'description': traverse_obj(
114 node
, ('edge_media_to_caption', 'edges', 0, 'node', 'text'), expected_type
=str),
115 'thumbnail': traverse_obj(
116 node
, 'display_url', 'thumbnail_src', 'display_src', expected_type
=url_or_none
),
117 'duration': float_or_none(node
.get('video_duration')),
118 'timestamp': int_or_none(node
.get('taken_at_timestamp')),
119 'view_count': int_or_none(node
.get('video_view_count')),
120 'comment_count': self
._get
_count
(node
, 'comments', 'preview_comment', 'to_comment', 'to_parent_comment'),
121 'like_count': self
._get
_count
(node
, 'likes', 'preview_like'),
124 def _extract_product_media(self
, product_media
):
125 media_id
= product_media
.get('code') or product_media
.get('id')
126 vcodec
= product_media
.get('video_codec')
127 dash_manifest_raw
= product_media
.get('video_dash_manifest')
128 videos_list
= product_media
.get('video_versions')
129 if not (dash_manifest_raw
or videos_list
):
133 'format_id': format
.get('id'),
134 'url': format
.get('url'),
135 'width': format
.get('width'),
136 'height': format
.get('height'),
138 } for format
in videos_list
or []]
139 if dash_manifest_raw
:
140 formats
.extend(self
._parse
_mpd
_formats
(self
._parse
_xml
(dash_manifest_raw
, media_id
), mpd_id
='dash'))
141 self
._sort
_formats
(formats
)
144 'url': thumbnail
.get('url'),
145 'width': thumbnail
.get('width'),
146 'height': thumbnail
.get('height')
147 } for thumbnail
in traverse_obj(product_media
, ('image_versions2', 'candidates')) or []]
150 'duration': float_or_none(product_media
.get('video_duration')),
152 'thumbnails': thumbnails
155 def _extract_product(self
, product_info
):
156 if isinstance(product_info
, list):
157 product_info
= product_info
[0]
159 user_info
= product_info
.get('user') or {}
161 'id': product_info
.get('code') or product_info
.get('id'),
162 'title': product_info
.get('title') or f
'Video by {user_info.get("username")}',
163 'description': traverse_obj(product_info
, ('caption', 'text'), expected_type
=str_or_none
),
164 'timestamp': int_or_none(product_info
.get('taken_at')),
165 'channel': user_info
.get('username'),
166 'uploader': user_info
.get('full_name'),
167 'uploader_id': str_or_none(user_info
.get('pk')),
168 'view_count': int_or_none(product_info
.get('view_count')),
169 'like_count': int_or_none(product_info
.get('like_count')),
170 'comment_count': int_or_none(product_info
.get('comment_count')),
172 'Referer': 'https://www.instagram.com/',
175 carousel_media
= product_info
.get('carousel_media')
180 'title': f
'Post by {user_info.get("username")}',
183 **self
._extract
_product
_media
(product_media
),
184 } for product_media
in carousel_media
],
189 **self
._extract
_product
_media
(product_info
)
193 class InstagramIOSIE(InfoExtractor
):
194 IE_DESC
= 'IOS instagram:// URL'
195 _VALID_URL
= r
'instagram://media\?id=(?P<id>[\d_]+)'
197 'url': 'instagram://media?id=482584233761418119',
198 'md5': '0d2da106a9d2631273e192b372806516',
202 'title': 'Video by naomipq',
203 'description': 'md5:1f17f0ab29bd6fe2bfad705f58de3cb8',
204 'thumbnail': r
're:^https?://.*\.jpg',
206 'timestamp': 1371748545,
207 'upload_date': '20130620',
208 'uploader_id': 'naomipq',
209 'uploader': 'B E A U T Y F O R A S H E S',
211 'comment_count': int,
214 'add_ie': ['Instagram']
217 def _get_id(self
, id):
218 """Source: https://stackoverflow.com/questions/24437823/getting-instagram-post-url-from-media-id"""
219 chrs
= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
220 media_id
= int(id.split('_')[0])
224 media_id
= (media_id
- r
) // 64
225 shortened_id
= chrs
[r
] + shortened_id
228 def _real_extract(self
, url
):
230 '_type': 'url_transparent',
231 'url': f
'http://instagram.com/tv/{self._get_id(self._match_id(url))}/',
232 'ie_key': 'Instagram',
236 class InstagramIE(InstagramBaseIE
):
237 _VALID_URL
= r
'(?P<url>https?://(?:www\.)?instagram\.com(?:/[^/]+)?/(?:p|tv|reel)/(?P<id>[^/?#&]+))'
239 'url': 'https://instagram.com/p/aye83DjauH/?foo=bar#abc',
240 'md5': '0d2da106a9d2631273e192b372806516',
244 'title': 'Video by naomipq',
245 'description': 'md5:1f17f0ab29bd6fe2bfad705f58de3cb8',
246 'thumbnail': r
're:^https?://.*\.jpg',
248 'timestamp': 1371748545,
249 'upload_date': '20130620',
250 'uploader_id': '2815873',
251 'uploader': 'B E A U T Y F O R A S H E S',
252 'channel': 'naomipq',
254 'comment_count': int,
258 # missing description
259 'url': 'https://www.instagram.com/p/BA-pQFBG8HZ/?taken-by=britneyspears',
263 'title': 'Video by britneyspears',
264 'thumbnail': r
're:^https?://.*\.jpg',
266 'timestamp': 1453760977,
267 'upload_date': '20160125',
268 'uploader_id': '12246775',
269 'uploader': 'Britney Spears',
270 'channel': 'britneyspears',
272 'comment_count': int,
276 'skip_download': True,
280 'url': 'https://www.instagram.com/p/BQ0eAlwhDrw/',
302 'title': 'Post by instagram',
303 'description': 'md5:0f9203fc6a2ce4d228da5754bcf54957',
307 'url': 'https://www.instagram.com/tv/BkfuX9UB-eK/',
311 'title': 'Fingerboarding Tricks with @cass.fb',
312 'thumbnail': r
're:^https?://.*\.jpg',
314 'timestamp': 1530032919,
315 'upload_date': '20180626',
316 'uploader_id': '25025320',
317 'uploader': 'Instagram',
318 'channel': 'instagram',
320 'comment_count': int,
322 'description': 'Meet Cass Hirst (@cass.fb), a fingerboarding pro who can perform tiny ollies and kickflips while blindfolded.',
325 'url': 'https://instagram.com/p/-Cmh1cukG2/',
326 'only_matching': True,
328 'url': 'http://instagram.com/p/9o6LshA7zy/embed/',
329 'only_matching': True,
331 'url': 'https://www.instagram.com/tv/aye83DjauH/',
332 'only_matching': True,
334 'url': 'https://www.instagram.com/reel/CDUMkliABpa/',
335 'only_matching': True,
337 'url': 'https://www.instagram.com/marvelskies.fc/reel/CWqAgUZgCku/',
338 'only_matching': True,
342 def _extract_embed_url(webpage
):
344 r
'<iframe[^>]+src=(["\'])(?P
<url
>(?
:https?
:)?
//(?
:www\
.)?instagram\
.com
/p
/[^
/]+/embed
.*?
)\
1',
347 return mobj.group('url
')
349 blockquote_el = get_element_by_attribute(
350 'class', 'instagram
-media
', webpage)
351 if blockquote_el is None:
355 r'<a
[^
>]+href
=([\'"])(?P<link>[^\'"]+)\
1', blockquote_el)
357 return mobj.group('link
')
359 def _real_extract(self, url):
360 video_id, url = self._match_valid_url(url).group('id', 'url
')
361 webpage, urlh = self._download_webpage_handle(url, video_id)
362 if 'www
.instagram
.com
/accounts
/login
' in urlh.geturl():
363 self.report_warning('Main webpage
is locked behind the login page
. '
364 'Retrying
with embed
webpage (Note that some metadata might be missing
)')
365 webpage = self._download_webpage(
366 'https
://www
.instagram
.com
/p
/%s/embed
/' % video_id, video_id, note='Downloading embed webpage
')
368 shared_data = self._parse_json(
370 r'window\
._sharedData\s
*=\s
*({.+?}
);',
371 webpage, 'shared data
', default='{}'),
372 video_id, fatal=False)
373 media = traverse_obj(
375 ('entry_data
', 'PostPage
', 0, 'graphql
', 'shortcode_media
'),
376 ('entry_data
', 'PostPage
', 0, 'media
'),
379 # _sharedData.entry_data.PostPage is empty when authenticated (see
380 # https://github.com/ytdl-org/youtube-dl/pull/22880)
382 additional_data = self._parse_json(
384 r'window\
.__additionalDataLoaded\s
*\
(\s
*[^
,]+,\s
*({.+?}
)\s
*\
);',
385 webpage, 'additional data
', default='{}'),
386 video_id, fatal=False)
387 product_item = traverse_obj(additional_data, ('items
', 0), expected_type=dict)
389 return self._extract_product(product_item)
390 media = traverse_obj(additional_data, ('graphql
', 'shortcode_media
'), 'shortcode_media
', expected_type=dict) or {}
392 if not media and 'www
.instagram
.com
/accounts
/login
' in urlh.geturl():
393 self.raise_login_required('You need to log
in to access this content
')
395 username = traverse_obj(media, ('owner
', 'username
')) or self._search_regex(
396 r'"owner"\s
*:\s
*{\s
*"username"\s
*:\s
*"(.+?)"', webpage, 'username
', fatal=False)
399 traverse_obj(media, ('edge_media_to_caption
', 'edges
', 0, 'node
', 'text
'), expected_type=str)
400 or media.get('caption
'))
402 description = self._search_regex(
403 r'"caption"\s
*:\s
*"(.+?)"', webpage, 'description
', default=None)
404 if description is not None:
405 description = lowercase_escape(description)
407 video_url = media.get('video_url
')
409 nodes = traverse_obj(media, ('edge_sidecar_to_children
', 'edges
', ..., 'node
'), expected_type=dict) or []
411 return self.playlist_result(
412 self._extract_nodes(nodes, True), video_id,
413 format_field(username, template='Post by
%s'), description)
415 video_url = self._og_search_video_url(webpage, secure=False)
419 'width
': self._get_dimension('width
', media, webpage),
420 'height
': self._get_dimension('height
', media, webpage),
422 dash = traverse_obj(media, ('dash_info
', 'video_dash_manifest
'))
424 formats.extend(self._parse_mpd_formats(self._parse_xml(dash, video_id), mpd_id='dash
'))
425 self._sort_formats(formats)
427 comment_data = traverse_obj(media, ('edge_media_to_parent_comment
', 'edges
'))
429 'author
': traverse_obj(comment_dict, ('node
', 'owner
', 'username
')),
430 'author_id
': traverse_obj(comment_dict, ('node
', 'owner
', 'id')),
431 'id': traverse_obj(comment_dict, ('node
', 'id')),
432 'text
': traverse_obj(comment_dict, ('node
', 'text
')),
433 'timestamp
': traverse_obj(comment_dict, ('node
', 'created_at
'), expected_type=int_or_none),
434 } for comment_dict in comment_data] if comment_data else None
436 display_resources = (
437 media.get('display_resources
')
438 or [{'src': media.get(key)} for key in ('display_src
', 'display_url
')]
439 or [{'src': self._og_search_thumbnail(webpage)}])
441 'url
': thumbnail['src
'],
442 'width
': thumbnail.get('config_width
'),
443 'height
': thumbnail.get('config_height
'),
444 } for thumbnail in display_resources if thumbnail.get('src
')]
449 'title
': media.get('title
') or 'Video by
%s' % username,
450 'description
': description,
451 'duration
': float_or_none(media.get('video_duration
')),
452 'timestamp
': traverse_obj(media, 'taken_at_timestamp
', 'date
', expected_type=int_or_none),
453 'uploader_id
': traverse_obj(media, ('owner
', 'id')),
454 'uploader
': traverse_obj(media, ('owner
', 'full_name
')),
456 'like_count
': self._get_count(media, 'likes
', 'preview_like
') or str_to_int(self._search_regex(
457 r'data
-log
-event
="likeCountClick"[^
>]*>[^\d
]*([\d
,\
.]+)', webpage, 'like count
', fatal=False)),
458 'comment_count
': self._get_count(media, 'comments
', 'preview_comment
', 'to_comment
', 'to_parent_comment
'),
459 'comments
': comments,
460 'thumbnails
': thumbnails,
462 'Referer
': 'https
://www
.instagram
.com
/',
467 class InstagramPlaylistBaseIE(InstagramBaseIE):
468 _gis_tmpl = None # used to cache GIS request type
470 def _parse_graphql(self, webpage, item_id):
471 # Reads a webpage and returns its GraphQL data.
472 return self._parse_json(
474 r'sharedData\s
*=\s
*({.+?}
)\s
*;\s
*[<\n]', webpage, 'data
'),
477 def _extract_graphql(self, data, url):
478 # Parses GraphQL queries containing videos and generates a playlist.
479 uploader_id = self._match_id(url)
480 csrf_token = data['config
']['csrf_token
']
481 rhx_gis = data.get('rhx_gis
') or '3c7ca9dcefcf966d11dacf1f151335e8
'
484 for page_num in itertools.count(1):
489 variables.update(self._query_vars_for(data))
490 variables = json.dumps(variables)
493 gis_tmpls = [self._gis_tmpl]
498 '%s:%s' % (rhx_gis, csrf_token),
499 '%s:%s:%s' % (rhx_gis, csrf_token, self.get_param('http_headers
')['User
-Agent
']),
502 # try all of the ways to generate a GIS query, and not only use the
503 # first one that works, but cache it for future requests
504 for gis_tmpl in gis_tmpls:
506 json_data = self._download_json(
507 'https
://www
.instagram
.com
/graphql
/query
/', uploader_id,
508 'Downloading JSON page
%d' % page_num, headers={
509 'X
-Requested
-With
': 'XMLHttpRequest
',
510 'X
-Instagram
-GIS
': hashlib.md5(
511 ('%s:%s' % (gis_tmpl, variables)).encode('utf
-8')).hexdigest(),
513 'query_hash
': self._QUERY_HASH,
514 'variables
': variables,
516 media = self._parse_timeline_from(json_data)
517 self._gis_tmpl = gis_tmpl
519 except ExtractorError as e:
520 # if it's an error caused by a bad query
, and there are
521 # more GIS templates to try, ignore it and keep trying
522 if isinstance(e
.cause
, compat_HTTPError
) and e
.cause
.code
== 403:
523 if gis_tmpl
!= gis_tmpls
[-1]:
527 nodes
= traverse_obj(media
, ('edges', ..., 'node'), expected_type
=dict) or []
530 yield from self
._extract
_nodes
(nodes
)
532 has_next_page
= traverse_obj(media
, ('page_info', 'has_next_page'))
533 cursor
= traverse_obj(media
, ('page_info', 'end_cursor'), expected_type
=str)
534 if not has_next_page
or not cursor
:
537 def _real_extract(self
, url
):
538 user_or_tag
= self
._match
_id
(url
)
539 webpage
= self
._download
_webpage
(url
, user_or_tag
)
540 data
= self
._parse
_graphql
(webpage
, user_or_tag
)
542 self
._set
_cookie
('instagram.com', 'ig_pr', '1')
544 return self
.playlist_result(
545 self
._extract
_graphql
(data
, url
), user_or_tag
, user_or_tag
)
548 class InstagramUserIE(InstagramPlaylistBaseIE
):
549 _VALID_URL
= r
'https?://(?:www\.)?instagram\.com/(?P<id>[^/]{2,})/?(?:$|[?#])'
550 IE_DESC
= 'Instagram user profile'
551 IE_NAME
= 'instagram:user'
553 'url': 'https://instagram.com/porsche',
560 'extract_flat': True,
561 'skip_download': True,
566 _QUERY_HASH
= '42323d64886122307be10013ad2dcc44',
569 def _parse_timeline_from(data
):
570 # extracts the media timeline data from a GraphQL result
571 return data
['data']['user']['edge_owner_to_timeline_media']
574 def _query_vars_for(data
):
575 # returns a dictionary of variables to add to the timeline query based
576 # on the GraphQL of the original page
578 'id': data
['entry_data']['ProfilePage'][0]['graphql']['user']['id']
582 class InstagramTagIE(InstagramPlaylistBaseIE
):
583 _VALID_URL
= r
'https?://(?:www\.)?instagram\.com/explore/tags/(?P<id>[^/]+)'
584 IE_DESC
= 'Instagram hashtag search URLs'
585 IE_NAME
= 'instagram:tag'
587 'url': 'https://instagram.com/explore/tags/lolcats',
592 'playlist_count': 50,
594 'extract_flat': True,
595 'skip_download': True,
600 _QUERY_HASH
= 'f92f56d47dc7a55b606908374b43a314',
603 def _parse_timeline_from(data
):
604 # extracts the media timeline data from a GraphQL result
605 return data
['data']['hashtag']['edge_hashtag_to_media']
608 def _query_vars_for(data
):
609 # returns a dictionary of variables to add to the timeline query based
610 # on the GraphQL of the original page
613 data
['entry_data']['TagPage'][0]['graphql']['hashtag']['name']
617 class InstagramStoryIE(InstagramBaseIE
):
618 _VALID_URL
= r
'https?://(?:www\.)?instagram\.com/stories/(?P<user>[^/]+)/(?P<id>\d+)'
619 IE_NAME
= 'instagram:story'
622 'url': 'https://www.instagram.com/stories/highlights/18090946048123978/',
624 'id': '18090946048123978',
627 'playlist_mincount': 50
630 def _real_extract(self
, url
):
631 username
, story_id
= self
._match
_valid
_url
(url
).groups()
633 story_info_url
= f
'{username}/{story_id}/?__a=1' if username
== 'highlights' else f
'{username}/?__a=1'
634 story_info
= self
._download
_json
(f
'https://www.instagram.com/stories/{story_info_url}', story_id
, headers
={
635 'X-IG-App-ID': 936619743392459,
638 'X-Requested-With': 'XMLHttpRequest',
641 user_id
= story_info
['user']['id']
642 highlight_title
= traverse_obj(story_info
, ('highlight', 'title'))
644 story_info_url
= user_id
if username
!= 'highlights' else f
'highlight:{story_id}'
645 videos
= self
._download
_json
(f
'https://i.instagram.com/api/v1/feed/reels_media/?reel_ids={story_info_url}', story_id
, headers
={
646 'X-IG-App-ID': 936619743392459,
651 full_name
= traverse_obj(videos
, ('user', 'full_name'))
654 if not (username
and username
!= 'highlights' and full_name
):
655 user_info
= self
._download
_json
(
656 f
'https://i.instagram.com/api/v1/users/{user_id}/info/', story_id
, headers
={
657 '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)',
658 }, note
='Downloading user info')
660 username
= traverse_obj(user_info
, ('user', 'username')) or username
661 full_name
= traverse_obj(user_info
, ('user', 'full_name')) or full_name
663 highlights
= traverse_obj(videos
, (f
'highlight:{story_id}', 'items'), (str(user_id
), 'items'))
664 return self
.playlist_result([{
665 **self
._extract
_product
(highlight
),
666 'title': f
'Story by {username}',
667 'uploader': full_name
,
668 'uploader_id': user_id
,
669 } for highlight
in highlights
], playlist_id
=story_id
, playlist_title
=highlight_title
)