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

使用Python Requests登录Instagram获取账号信息遇useragent mismatch错误

解决Instagram接口调用的"User-Agent不匹配"错误

错误原因

你调用的https://i.instagram.com/api/v1/users/{userid}/info/是Instagram的移动端专属API接口,这类接口会严格校验请求的User-Agent标识,要求必须是移动端设备(手机浏览器或Instagram App)的UA字符串,而你当前使用的是桌面Chrome浏览器的UA,因此触发了"useragent mismatch"(用户代理不匹配)错误。

解决方案

1. 替换为移动端User-Agent

选择一个合法的移动端UA,比如Instagram官方App的UA或者手机浏览器的UA:

  • Instagram iOS App示例UA:Instagram 277.0.0.12.109 (iPhone14,3; iOS 16_0; en_US; en-US; scale=3.00; 1284x2778; 202165599)
  • 移动端Safari示例UA:Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Mobile/15E148 Safari/604.1

2. 补充移动端API必要请求头

移动端API还需要额外的x-ig-app-id头,这个是Instagram对应客户端的固定ID,iOS端常用的是936619743392459,Android端是124024574287414,任选其一即可。

修改后的完整代码

import requests
import re

s = requests.session()
# 初始化会话,获取初始cookie
s.get("https://www.instagram.com/")

payload = {
    "enc_password": "#PWD_INSTAGRAM_BROWSER:0:0:hello123",
    "queryParams": {},
    "trustedDeviceRecords": {},
    "username": "censor",
}

# 登录用的桌面端UA(保持不变,因为登录接口是web端)
headers_web = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36"
}

# 获取csrftoken
cookie_cek = s.get("https://www.instagram.com/api/v1/web/accounts/login/ajax/", headers=headers_web)
csrftoken = s.cookies.get("csrftoken")

headers_login = {
    "User-Agent": headers_web["User-Agent"],
    "x-csrftoken": csrftoken,
}

# 执行登录
r = s.post(
    "https://www.instagram.com/api/v1/web/accounts/login/ajax/",
    data=payload,
    headers=headers_login,
)
print(r.text)

# 获取目标用户ID
hesap_bilgisi_cek = s.get("https://www.instagram.com/kevin/")
search_pattern = re.compile(rb'"id":"(\d+)"')
match = search_pattern.search(hesap_bilgisi_cek.content)
if match:
    userid = match.group(1).decode("utf-8")
    print("userid:", userid)
else:
    print("获取用户ID失败")

# 移动端API专用请求头(关键修改部分)
headers_mobile = {
    "User-Agent": "Instagram 277.0.0.12.109 (iPhone14,3; iOS 16_0; en_US; en-US; scale=3.00; 1284x2778; 202165599)",
    "x-ig-app-id": "936619743392459",
    "x-csrftoken": csrftoken,
}

# 调用移动端API获取用户信息
get_account_info = s.get(
    f"https://i.instagram.com/api/v1/users/{userid}/info/",
    headers=headers_mobile
)
print(get_account_info.content)

额外说明

  • 登录接口https://www.instagram.com/api/v1/web/accounts/login/ajax/属于web端接口,使用桌面UA没问题;但i.instagram.com域名下的接口都是移动端API,必须用移动端UA和对应app id。
  • 若后续仍出现验证错误,可尝试更新UA为最新版本的Instagram App UA,或添加x-requested-with: XMLHttpRequest等额外头。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 18:45:09