如何用JavaScript从链接下载Instagram公开帖子的图片或视频?
用JavaScript下载Instagram公开帖子媒体的可行方案
方法1:利用非官方嵌入接口获取媒体信息(个人临时使用)
Instagram的公开帖子支持通过添加__a=1参数的接口返回结构化JSON数据,无需登录即可获取媒体资源地址,步骤如下:
- 把目标帖子链接(比如
https://www.instagram.com/p/ABC123/)修改为https://www.instagram.com/p/ABC123/?__a=1 - 在浏览器控制台执行以下代码(仅适合个人非商业用途):
fetch('https://www.instagram.com/p/ABC123/?__a=1') .then(res => res.json()) .then(data => { const media = data.graphql.shortcode_media; // 处理单张图片 if (media.__typename === 'GraphImage') { const a = document.createElement('a'); a.href = media.display_url; a.download = `ig-image-${media.shortcode}.jpg`; a.click(); } // 处理单条视频 else if (media.__typename === 'GraphVideo') { const a = document.createElement('a'); a.href = media.video_url; a.download = `ig-video-${media.shortcode}.mp4`; a.click(); } // 处理多图/视频轮播帖 else if (media.__typename === 'GraphSidecar') { media.edge_sidecar_to_children.edges.forEach((item, idx) => { const node = item.node; const url = node.__typename === 'GraphImage' ? node.display_url : node.video_url; const a = document.createElement('a'); a.href = url; a.download = `ig-media-${media.shortcode}-${idx+1}.${node.__typename === 'GraphImage' ? 'jpg' : 'mp4'}`; a.click(); }); } }) .catch(err => console.error('获取数据失败:', err));
- 注意:该接口属于非官方接口,Instagram可能随时调整参数或限制访问,仅适合临时使用。
方法2:官方Graph API(合规长期方案)
如果是商业项目,必须使用官方API避免违规,步骤如下:
- 在Facebook开发者平台创建应用,申请Instagram Graph API权限并获取
access_token - 通过帖子
shortcode查询媒体信息,示例代码(需在后端执行,避免前端暴露access_token):
// 后端请求示例 fetch('https://graph.instagram.com/ABC123?fields=id,media_type,media_url&access_token=YOUR_VALID_ACCESS_TOKEN') .then(res => res.json()) .then(data => { // 单图/单视频下载 if (data.media_type === 'IMAGE' || data.media_type === 'VIDEO') { // 直接使用data.media_url作为下载地址 } // 轮播帖需额外获取子媒体 else if (data.media_type === 'CAROUSEL_ALBUM') { fetch(`https://graph.instagram.com/${data.id}/children?fields=media_type,media_url&access_token=YOUR_VALID_ACCESS_TOKEN`) .then(res => res.json()) .then(children => { children.data.forEach(item => { // 遍历使用item.media_url下载 }); }); } });
- 优势:稳定合规,不会被反爬机制拦截,适合长期维护的项目。
重要提醒
- 频繁请求非官方接口可能触发Instagram的反爬限制,导致IP被临时封禁
- 所有获取和下载行为必须符合Instagram的服务条款,禁止用于批量爬取或商业侵权用途
内容的提问来源于stack exchange,提问作者sarfrazanwar
相关产品推荐
相关产品推荐

