2021年如何在网站展示Instagram粉丝数 旧PHP实现全部失效求解决方案
失效原因
你之前使用的所有方案都已经失效,核心是2020年末Instagram调整了公开数据访问规则:
- 不带登录态直接请求
__a=1接口会直接返回403或重定向到登录页 - 公开个人主页的HTML结构、字段名全部更新,旧正则和
window._sharedData提取逻辑都不生效 - 直接用
file_get_contents请求会被反爬机制拦截,返回验证码页面而非实际主页内容
2021年可用实现方案
方案1:官方合规方案(推荐,长期稳定)
使用Instagram Basic Display API获取公开账号数据,完全符合平台规则,不会被反爬拦截:
- 前往Meta开发者平台创建应用,添加「Instagram Basic Display」产品,完成应用配置后添加目标账号为测试用户,获取长有效期访问令牌(有效期60天,可自动刷新)
- 对应PHP代码示例:
<?php $access_token = '你获取的长寿命访问令牌'; $user_id = '目标账号的数字ID'; $api_url = "https://graph.instagram.com/$user_id?fields=id,username,followers_count,follows_count&access_token=$access_token"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $api_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $response = curl_exec($ch); curl_close($ch); $data = json_decode($response, true); if (isset($data['followers_count'])) { $followers = $data['followers_count']; echo "粉丝数:" . $followers; } ?>
方案2:无API抓取方案(适合小流量使用,有被反爬风险)
通过cURL模拟正常浏览器请求头,绕过基础反爬,从返回的HTML中提取粉丝数字段:
<?php $username = '目标账号用户名'; $url = "https://www.instagram.com/$username/"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'); curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept-Language: zh-CN,zh;q=0.9,en;q=0.8']); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $html = curl_exec($ch); curl_close($ch); if (preg_match('/"edge_followed_by":{"count":([0-9]+)}/', $html, $matches)) { $followers = $matches[1]; echo $username . "的粉丝数:" . $followers; } else { echo "获取失败,请检查账号是否公开,或稍后重试"; } ?>
注意事项
- 无API抓取方案不要高频调用,否则会被Instagram临时封禁你的服务器IP
- 仅公开账号可以正常获取数据,私密账号无法拿到粉丝数信息
内容的提问来源于stack exchange,提问作者chechu
相关产品推荐
相关产品推荐

