1 from __future__ import unicode_literals
8 from .common import InfoExtractor
9 from ..compat import compat_str
11 get_element_by_attribute,
19 class InstagramIE(InfoExtractor):
20 _VALID_URL = r'(?P<url>https?://(?:www\.)?instagram\.com/p/(?P<id>[^/?#&]+))'
22 'url': 'https://instagram.com/p/aye83DjauH/?foo=bar#abc',
23 'md5': '0d2da106a9d2631273e192b372806516',
27 'title': 'Video by naomipq',
28 'description': 'md5:1f17f0ab29bd6fe2bfad705f58de3cb8',
29 'thumbnail': r're:^https?://.*\.jpg',
30 'timestamp': 1371748545,
31 'upload_date': '20130620',
32 'uploader_id': 'naomipq',
33 'uploader': 'Naomi Leonor Phan-Quang',
40 'url': 'https://www.instagram.com/p/BA-pQFBG8HZ/?taken-by=britneyspears',
44 'title': 'Video by britneyspears',
45 'thumbnail': r're:^https?://.*\.jpg',
46 'timestamp': 1453760977,
47 'upload_date': '20160125',
48 'uploader_id': 'britneyspears',
49 'uploader': 'Britney Spears',
55 'skip_download': True,
59 'url': 'https://www.instagram.com/p/BQ0eAlwhDrw/',
81 'title': 'Post by instagram',
82 'description': 'md5:0f9203fc6a2ce4d228da5754bcf54957',
85 'url': 'https://instagram.com/p/-Cmh1cukG2/',
86 'only_matching': True,
88 'url': 'http://instagram.com/p/9o6LshA7zy/embed/',
89 'only_matching': True,
93 def _extract_embed_url(webpage):
95 r'<iframe[^>]+src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?instagram\.com/p/[^/]+/embed.*?)\1',
98 return mobj.group('url')
100 blockquote_el = get_element_by_attribute(
101 'class', 'instagram-media', webpage)
102 if blockquote_el is None:
106 r'<a[^>]+href=([\'"])(?P<link>[^\'"]+)\1', blockquote_el)
108 return mobj.group('link')
110 def _real_extract(self, url):
111 mobj = re.match(self._VALID_URL, url)
112 video_id = mobj.group('id')
113 url = mobj.group('url')
115 webpage = self._download_webpage(url, video_id)
117 (video_url, description, thumbnail, timestamp, uploader,
118 uploader_id, like_count, comment_count, comments, height,
121 shared_data = self._parse_json(
123 r'window\._sharedData\s*=\s*({.+?});',
124 webpage, 'shared data', default='{}'),
125 video_id, fatal=False)
129 (lambda x: x['entry_data']['PostPage'][0]['graphql']['shortcode_media'],
130 lambda x: x['entry_data']['PostPage'][0]['media']),
133 video_url = media.get('video_url')
134 height = int_or_none(media.get('dimensions', {}).get('height'))
135 width = int_or_none(media.get('dimensions', {}).get('width'))
136 description = try_get(
137 media, lambda x: x['edge_media_to_caption']['edges'][0]['node']['text'],
138 compat_str) or media.get('caption')
139 thumbnail = media.get('display_src')
140 timestamp = int_or_none(media.get('taken_at_timestamp') or media.get('date'))
141 uploader = media.get('owner', {}).get('full_name')
142 uploader_id = media.get('owner', {}).get('username')
144 def get_count(key, kind):
145 return int_or_none(try_get(
146 media, (lambda x: x['edge_media_%s' % key]['count'],
147 lambda x: x['%ss' % kind]['count'])))
148 like_count = get_count('preview_like', 'like')
149 comment_count = get_count('to_comment', 'comment')
152 'author': comment.get('user', {}).get('username'),
153 'author_id': comment.get('user', {}).get('id'),
154 'id': comment.get('id'),
155 'text': comment.get('text'),
156 'timestamp': int_or_none(comment.get('created_at')),
157 } for comment in media.get(
158 'comments', {}).get('nodes', []) if comment.get('text')]
161 media, lambda x: x['edge_sidecar_to_children']['edges'],
165 for edge_num, edge in enumerate(edges, start=1):
166 node = try_get(edge, lambda x: x['node'], dict)
169 node_video_url = try_get(node, lambda x: x['video_url'], compat_str)
170 if not node_video_url:
173 'id': node.get('shortcode') or node['id'],
174 'title': 'Video %d' % edge_num,
175 'url': node_video_url,
176 'thumbnail': node.get('display_url'),
177 'width': int_or_none(try_get(node, lambda x: x['dimensions']['width'])),
178 'height': int_or_none(try_get(node, lambda x: x['dimensions']['height'])),
179 'view_count': int_or_none(node.get('video_view_count')),
181 return self.playlist_result(
183 'Post by %s' % uploader_id if uploader_id else None,
187 video_url = self._og_search_video_url(webpage, secure=False)
196 uploader_id = self._search_regex(
197 r'"owner"\s*:\s*{\s*"username"\s*:\s*"(.+?)"',
198 webpage, 'uploader id', fatal=False)
201 description = self._search_regex(
202 r'"caption"\s*:\s*"(.+?)"', webpage, 'description', default=None)
203 if description is not None:
204 description = lowercase_escape(description)
207 thumbnail = self._og_search_thumbnail(webpage)
213 'title': 'Video by %s' % uploader_id,
214 'description': description,
215 'thumbnail': thumbnail,
216 'timestamp': timestamp,
217 'uploader_id': uploader_id,
218 'uploader': uploader,
219 'like_count': like_count,
220 'comment_count': comment_count,
221 'comments': comments,
225 class InstagramUserIE(InfoExtractor):
226 _VALID_URL = r'https?://(?:www\.)?instagram\.com/(?P<id>[^/]{2,})/?(?:$|[?#])'
227 IE_DESC = 'Instagram user profile'
228 IE_NAME = 'instagram:user'
230 'url': 'https://instagram.com/porsche',
237 'extract_flat': True,
238 'skip_download': True,
243 def _entries(self, data):
244 def get_count(suffix):
245 return int_or_none(try_get(
246 node, lambda x: x['edge_media_' + suffix]['count']))
248 uploader_id = data['entry_data']['ProfilePage'][0]['graphql']['user']['id']
249 csrf_token = data['config']['csrf_token']
250 rhx_gis = data.get('rhx_gis') or '3c7ca9dcefcf966d11dacf1f151335e8'
252 self._set_cookie('instagram.com', 'ig_pr', '1')
255 for page_num in itertools.count(1):
256 variables = json.dumps({
261 s = '%s:%s:%s:%s' % (rhx_gis, csrf_token, std_headers['User-Agent'], variables)
262 media = self._download_json(
263 'https://www.instagram.com/graphql/query/', uploader_id,
264 'Downloading JSON page %d' % page_num, headers={
265 'X-Requested-With': 'XMLHttpRequest',
266 'X-Instagram-GIS': hashlib.md5(s.encode('utf-8')).hexdigest(),
268 'query_hash': '472f257a40c653c64c666ce877d59d2b',
269 'variables': variables,
270 })['data']['user']['edge_owner_to_timeline_media']
272 edges = media.get('edges')
273 if not edges or not isinstance(edges, list):
277 node = edge.get('node')
278 if not node or not isinstance(node, dict):
280 if node.get('__typename') != 'GraphVideo' and node.get('is_video') is not True:
282 video_id = node.get('shortcode')
286 info = self.url_result(
287 'https://instagram.com/p/%s/' % video_id,
288 ie=InstagramIE.ie_key(), video_id=video_id)
290 description = try_get(
291 node, lambda x: x['edge_media_to_caption']['edges'][0]['node']['text'],
293 thumbnail = node.get('thumbnail_src') or node.get('display_src')
294 timestamp = int_or_none(node.get('taken_at_timestamp'))
296 comment_count = get_count('to_comment')
297 like_count = get_count('preview_like')
298 view_count = int_or_none(node.get('video_view_count'))
301 'description': description,
302 'thumbnail': thumbnail,
303 'timestamp': timestamp,
304 'comment_count': comment_count,
305 'like_count': like_count,
306 'view_count': view_count,
311 page_info = media.get('page_info')
312 if not page_info or not isinstance(page_info, dict):
315 has_next_page = page_info.get('has_next_page')
316 if not has_next_page:
319 cursor = page_info.get('end_cursor')
320 if not cursor or not isinstance(cursor, compat_str):
323 def _real_extract(self, url):
324 username = self._match_id(url)
326 webpage = self._download_webpage(url, username)
328 data = self._parse_json(
330 r'sharedData\s*=\s*({.+?})\s*;\s*[<\n]', webpage, 'data'),
333 return self.playlist_result(
334 self._entries(data), username, username)