You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP使用curl或file_get_contents无法抓取Instagram公共账号story JSON数据

问题根因及修复方案

1 最直接错误:Cookie请求头语法错误

你当前getContents方法里的Cookie请求头少了冒号,不符合HTTP头规范,Instagram服务端无法识别你传递的Cookie,直接拦截请求返回空内容:

// 错误写法:Cookie后面少了冒号
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Cookie ' . file_get_contents($this->cookieFile)
));

// 正确写法,同时补充其他必要请求头模拟浏览器行为
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Cookie: ' . file_get_contents($this->cookieFile),
    'Referer: https://www.instagram.com/',
    'Accept: application/json, text/javascript, */*; q=0.01',
    'X-Requested-With: XMLHttpRequest'
));

2 Cookie有效性校验

Instagram的GraphQL故事查询接口必须携带已登录账号的有效Cookie才能返回数据,你需要确认:

  • cookie.txt里的内容是从你浏览器登录Instagram后,F12网络面板随便找一个Instagram的请求,复制请求头里的完整Cookie值,不要手动修改
  • Cookie过期后要及时更新,Instagram的Cookie有效期一般在几天到几周不等,过期后接口会直接返回空数据

3 补充Curl错误排查逻辑

你可以在curl执行后增加错误和状态码判断,快速定位问题:

$cookieFile = __DIR__ . '/../storage/cookie.txt';
$userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36'; 

/**
 * @param string $url
 * @param bool $cookies
 * @return string
 */
public function getContents($url, $cookies = true)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Cookie: ' . file_get_contents($this->cookieFile),
        'Referer: https://www.instagram.com/',
        'Accept: application/json, text/javascript, */*; q=0.01',
        'X-Requested-With: XMLHttpRequest'
    ));
  
    $data = curl_exec($ch);
    // 新增错误排查逻辑
    if(curl_errno($ch)) {
        error_log('CURL请求错误:' . curl_error($ch));
    }
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if($httpCode != 200) {
        error_log('请求返回状态码异常:' . $httpCode);
        // 状态码说明:401=Cookie无效,403=触发反爬限制,404=请求参数错误
    }
    curl_close($ch);
    return $data;
}

4 其他注意事项

  • 不要短时间内频繁请求该接口,Instagram会针对IP做频率限制,触发后会临时封禁你的IP几个小时
  • 如果是服务器部署,尽量用住宅IP,机房IP很容易被Instagram的反爬策略识别拦截

内容的提问来源于stack exchange,提问作者Ns789

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 05:48:03