1 from __future__ import unicode_literals
8 from .common import InfoExtractor
9 from ..compat import compat_str
11 get_element_by_attribute,
18 class InstagramIE(InfoExtractor):
19 _VALID_URL = r'(?P<url>https?://(?:www\.)?instagram\.com/p/(?P<id>[^/?#&]+))'
21 'url': 'https://instagram.com/p/aye83DjauH/?foo=bar#abc',
22 'md5': '0d2da106a9d2631273e192b372806516',
26 'title': 'Video by naomipq',
27 'description': 'md5:1f17f0ab29bd6fe2bfad705f58de3cb8',
28 'thumbnail': r're:^https?://.*\.jpg',
29 'timestamp': 1371748545,
30 'upload_date': '20130620',
31 'uploader_id': 'naomipq',
32 'uploader': 'Naomi Leonor Phan-Quang',
39 'url': 'https://www.instagram.com/p/BA-pQFBG8HZ/?taken-by=britneyspears',
43 'title': 'Video by britneyspears',
44 'thumbnail': r're:^https?://.*\.jpg',
45 'timestamp': 1453760977,
46 'upload_date': '20160125',
47 'uploader_id': 'britneyspears',
48 'uploader': 'Britney Spears',
54 'skip_download': True,
58 'url': 'https://www.instagram.com/p/BQ0eAlwhDrw/',
80 'title': 'Post by instagram',
81 'description': 'md5:0f9203fc6a2ce4d228da5754bcf54957',
84 'url': 'https://instagram.com/p/-Cmh1cukG2/',
85 'only_matching': True,
87 'url': 'http://instagram.com/p/9o6LshA7zy/embed/',
88 'only_matching': True,
92 def _extract_embed_url(webpage):
94 r'<iframe[^>]+src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?instagram\.com/p/[^/]+/embed.*?)\1',
97 return mobj.group('url')
99 blockquote_el = get_element_by_attribute(
100 'class', 'instagram-media', webpage)
101 if blockquote_el is None:
105 r'<a[^>]+href=([\'"])(?P<link>[^\'"]+)\1', blockquote_el)
107 return mobj.group('link')
109 def _real_extract(self, url):
110 mobj = re.match(self._VALID_URL, url)
111 video_id = mobj.group('id')
112 url = mobj.group('url')
114 webpage = self._download_webpage(url, video_id)
116 (video_url, description, thumbnail, timestamp, uploader,
117 uploader_id, like_count, comment_count, comments, height,
120 shared_data = self._parse_json(
122 r'window\._sharedData\s*=\s*({.+?});',
123 webpage, 'shared data', default='{}'),
124 video_id, fatal=False)
128 (lambda x: x['entry_data']['PostPage'][0]['graphql']['shortcode_media'],
129 lambda x: x['entry_data']['PostPage'][0]['media']),
132 video_url = media.get('video_url')
133 height = int_or_none(media.get('dimensions', {}).get('height'))
134 width = int_or_none(media.get('dimensions', {}).get('width'))
135 description = try_get(
136 media, lambda x: x['edge_media_to_caption']['edges'][0]['node']['text'],
137 compat_str) or media.get('caption')
138 thumbnail = media.get('display_src')
139 timestamp = int_or_none(media.get('taken_at_timestamp') or media.get('date'))
140 uploader = media.get('owner', {}).get('full_name')
141 uploader_id = media.get('owner', {}).get('username')
143 def get_count(key, kind):
144 return int_or_none(try_get(
145 media, (lambda x: x['edge_media_%s' % key]['count'],
146 lambda x: x['%ss' % kind]['count'])))
147 like_count = get_count('preview_like', 'like')
148 comment_count = get_count('to_comment', 'comment')
151 'author': comment.get('user', {}).get('username'),
152 'author_id': comment.get('user', {}).get('id'),
153 'id': comment.get('id'),
154 'text': comment.get('text'),
155 'timestamp': int_or_none(comment.get('created_at')),
156 } for comment in media.get(
157 'comments', {}).get('nodes', []) if comment.get('text')]
160 media, lambda x: x['edge_sidecar_to_children']['edges'],
164 for edge_num, edge in enumerate(edges, start=1):
165 node = try_get(edge, lambda x: x['node'], dict)
168 node_video_url = try_get(node, lambda x: x['video_url'], compat_str)
169 if not node_video_url:
172 'id': node.get('shortcode') or node['id'],
173 'title': 'Video %d' % edge_num,
174 'url': node_video_url,
175 'thumbnail': node.get('display_url'),
176 'width': int_or_none(try_get(node, lambda x: x['dimensions']['width'])),
177 'height': int_or_none(try_get(node, lambda x: x['dimensions']['height'])),
178 'view_count': int_or_none(node.get('video_view_count')),
180 return self.playlist_result(
182 'Post by %s' % uploader_id if uploader_id else None,
186 video_url = self._og_search_video_url(webpage, secure=False)
195 uploader_id = self._search_regex(
196 r'"owner"\s*:\s*{\s*"username"\s*:\s*"(.+?)"',
197 webpage, 'uploader id', fatal=False)
200 description = self._search_regex(
201 r'"caption"\s*:\s*"(.+?)"', webpage, 'description', default=None)
202 if description is not None:
203 description = lowercase_escape(description)
206 thumbnail = self._og_search_thumbnail(webpage)
212 'title': 'Video by %s' % uploader_id,
213 'description': description,
214 'thumbnail': thumbnail,
215 'timestamp': timestamp,
216 'uploader_id': uploader_id,
217 'uploader': uploader,
218 'like_count': like_count,
219 'comment_count': comment_count,
220 'comments': comments,
224 class InstagramUserIE(InfoExtractor):
225 _VALID_URL = r'https?://(?:www\.)?instagram\.com/(?P<id>[^/]{2,})/?(?:$|[?#])'
226 IE_DESC = 'Instagram user profile'
227 IE_NAME = 'instagram:user'
229 'url': 'https://instagram.com/porsche',
236 'extract_flat': True,
237 'skip_download': True,
242 def _entries(self, data):
243 def get_count(suffix):
244 return int_or_none(try_get(
245 node, lambda x: x['edge_media_' + suffix]['count']))
247 uploader_id = data['entry_data']['ProfilePage'][0]['graphql']['user']['id']
248 csrf_token = data['config']['csrf_token']
249 rhx_gis = data.get('rhx_gis') or '3c7ca9dcefcf966d11dacf1f151335e8'
251 self._set_cookie('instagram.com', 'ig_pr', '1')
254 for page_num in itertools.count(1):
255 variables = json.dumps({
260 s = '%s:%s:%s' % (rhx_gis, csrf_token, variables)
261 media = self._download_json(
262 'https://www.instagram.com/graphql/query/', uploader_id,
263 'Downloading JSON page %d' % page_num, headers={
264 'X-Requested-With': 'XMLHttpRequest',
265 'X-Instagram-GIS': hashlib.md5(s.encode('utf-8')).hexdigest(),
267 'query_hash': '472f257a40c653c64c666ce877d59d2b',
268 'variables': variables,
269 })['data']['user']['edge_owner_to_timeline_media']
271 edges = media.get('edges')
272 if not edges or not isinstance(edges, list):
276 node = edge.get('node')
277 if not node or not isinstance(node, dict):
279 if node.get('__typename') != 'GraphVideo' and node.get('is_video') is not True:
281 video_id = node.get('shortcode')
285 info = self.url_result(
286 'https://instagram.com/p/%s/' % video_id,
287 ie=InstagramIE.ie_key(), video_id=video_id)
289 description = try_get(
290 node, lambda x: x['edge_media_to_caption']['edges'][0]['node']['text'],
292 thumbnail = node.get('thumbnail_src') or node.get('display_src')
293 timestamp = int_or_none(node.get('taken_at_timestamp'))
295 comment_count = get_count('to_comment')
296 like_count = get_count('preview_like')
297 view_count = int_or_none(node.get('video_view_count'))
300 'description': description,
301 'thumbnail': thumbnail,
302 'timestamp': timestamp,
303 'comment_count': comment_count,
304 'like_count': like_count,
305 'view_count': view_count,
310 page_info = media.get('page_info')
311 if not page_info or not isinstance(page_info, dict):
314 has_next_page = page_info.get('has_next_page')
315 if not has_next_page:
318 cursor = page_info.get('end_cursor')
319 if not cursor or not isinstance(cursor, compat_str):
322 def _real_extract(self, url):
323 username = self._match_id(url)
325 webpage = self._download_webpage(url, username)
327 data = self._parse_json(
329 r'sharedData\s*=\s*({.+?})\s*;\s*[<\n]', webpage, 'data'),
332 return self.playlist_result(
333 self._entries(data), username, username)