WordPress调用Instagram公共API返回429错误解决方案求助
问题原因
你遇到的429错误不是主动请求量超标导致的,核心是Instagram的反爬机制识别到请求是服务端程序发起的,而非真实浏览器访问,即使请求次数很少也会直接拦截:
wp_remote_get默认发送的请求头特征非常明显,没有真实浏览器的UA、Accept等字段,很容易被Instagram标记为爬虫- 你的服务器所在IP段可能已经被其他同IP的爬虫请求触发了限流规则,即使你自己只发了几次请求也会被牵连
可行解决方案
1. 给请求添加模拟浏览器的头信息
修改wp_remote_get的调用参数,补充真实浏览器的请求头,避免被反爬识别。
2. 添加接口缓存
不要每次调用都请求Instagram接口,用WordPress的瞬态(Transient)功能把获取到的粉丝数据缓存2~4小时,大幅降低请求频率。
3. (可选)如果服务器IP被限制,可更换出口IP或使用代理转发请求
大部分场景下完成前两步即可解决问题。
修改后的示例代码
static function bk_read_count_social( $data, $social_type, $apiKey = '' ) { if($social_type == 'instagram') { $username = 'google'; // 先读缓存,缓存有效就直接返回 $cache_key = 'instagram_followers_' . $username; $cached_data = get_transient($cache_key); if($cached_data) { return $cached_data; } $publicApiUrl = 'https://www.instagram.com/'.$username.'/?__a=1'; // 模拟Chrome浏览器的请求头 $args = array( 'headers' => array( 'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36', 'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8', 'Accept-Language' => 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2', 'Accept-Encoding' => 'gzip, deflate, br', 'Connection' => 'keep-alive', 'Upgrade-Insecure-Requests' => '1', 'Sec-Fetch-Dest' => 'document', 'Sec-Fetch-Mode' => 'navigate', 'Sec-Fetch-Site' => 'none', 'Sec-Fetch-User' => '?1' ), 'timeout' => 10, 'sslverify' => false ); $response = wp_remote_get($publicApiUrl, $args); $instagramArgs = array( 'followers' => '', 'username' => $username ); if (!is_wp_error($response) && $response['response']['code'] !== 429) { $body = json_decode(wp_remote_retrieve_body($response), true); // 补上原代码缺失的响应体提取、JSON解析步骤 if(isset($body['graphql']['user']['edge_followed_by']['count'])) { $instagramArgs['followers'] = $body['graphql']['user']['edge_followed_by']['count']; // 缓存3小时 set_transient($cache_key, $instagramArgs, 3 * HOUR_IN_SECONDS); } } else { error_log('Unable to retrieve Instagram API'); error_log(print_r($response, true)); } return $instagramArgs; } // 其他社交平台逻辑可在此补充 return $data; }
额外注意事项
- 原代码直接取
$response['graphql']是错误的,wp_remote_get返回的响应体需要先通过wp_remote_retrieve_body提取再做JSON解析,否则无法正常拿到数据 - 如果后续Instagram调整了公开接口规则,
?__a=1的返回结构可能会变动,需要对应调整取值逻辑
内容的提问来源于stack exchange,提问作者CWSites
相关产品推荐
相关产品推荐

