这段 Python 脚本是一个用于抓取 Instagram 用户公开信息 的工具,它通过 Instagram 的非公开 API 接口(web_profile_info)模拟浏览器行为来实现数据的获取。下面是详细解析:


💡 总体功能

  • 利用 requests 模拟浏览器请求。
  • 携带浏览器的 Cookies 与 headers,从 Instagram 获取指定用户名的公开信息。
  • 解析返回的 JSON 数据并打印关键信息(如用户名、粉丝数、是否私人账户等)。

📦 模块分析

1
2
3
4
5
import requests
import json
import logging
import sys
from uuid import uuid4
  • requests: 发起 HTTP 请求。
  • json: 解析 JSON 格式数据。
  • logging: 用于记录日志。
  • uuid4: 引入但未使用,可以删除。
  • sys: 未使用,可删。

🧾 日志配置

1
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  • 设置日志输出格式:包含时间、日志级别和信息。

🔍 核心函数:获取用户信息

1
def get_user_info(cookies, target_username, headers):
  • cookies: 必须使用有效登录用户的 cookies,否则会被 Instagram 拒绝。
  • target_username: 要爬取的 Instagram 用户名。
  • headers: 模拟浏览器请求头。

请求 URL

1
url = f"https://i.instagram.com/api/v1/users/web_profile_info/?username={target_username}"

这是一个 非公开接口,用于获取用户资料数据。

错误处理与数据提取

1
2
3
response.raise_for_status()  # 抛出请求异常
data = response.json()
user_data = data.get("data", {}).get("user", {})
  • 获取并解析 JSON 数据。
  • 提取 user 信息块(若为空,则说明无此用户或接口被限流)。

输出结构

1
2
3
4
5
6
7
8
9
10
user_info = {
"username": user_data.get("username"),
"full_name": user_data.get("full_name"),
"biography": user_data.get("biography"),
"followers": user_data.get("edge_followed_by", {}).get("count"),
"following": user_data.get("edge_follow", {}).get("count"),
"posts": user_data.get("edge_owner_to_timeline_media", {}).get("count"),
"is_private": user_data.get("is_private"),
"external_url": user_data.get("external_url")
}
  • 输出包括:用户名、简介、粉丝数、关注数、发帖数、是否为私密账号、个人主页链接。

🚀 主函数 main()

设置了:

  • cookies:从登录的浏览器中提取(关键字段:sessionid, csrftoken 等)。
  • headers:伪装成浏览器访问。
  • 调用 get_user_info() 并打印结果。

⚠️ 注意事项

  1. 接口可能失效:Instagram 非公开 API 接口易变,可能随时封锁或验证。
  2. 需要有效登录 cookies:未登录或 cookies 失效会导致抓取失败。
  3. 违反服务条款:自动化抓取 Instagram 数据可能违反其使用政策。
  4. PGP HMAC 字段非必需x-ig-www-claim 可以为空或删去。

✅ 输出示例(可能是这样的):

1
2
3
4
5
6
7
8
9
2025-05-11 22:00:00 - INFO - 用户信息:
username: jjlin
full_name: 林俊杰
biography: 创作歌手 / JJ Lin
followers: 12500000
following: 120
posts: 290
is_private: False
external_url: https://linktr.ee/jjlin

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89

import requests
import json
import logging
import sys
from uuid import uuid4

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


def get_user_info(cookies, target_username, headers):
"""通过 Instagram API 获取用户信息"""
url = f"https://i.instagram.com/api/v1/users/web_profile_info/?username={target_username}"

try:
response = requests.get(url, headers=headers, cookies=cookies)
response.raise_for_status() # 检查请求是否成功

data = response.json()
user_data = data.get("data", {}).get("user", {})

if not user_data:
logger.error("未找到用户信息")
return None

user_info = {
"username": user_data.get("username"),
"full_name": user_data.get("full_name"),
"biography": user_data.get("biography"),
"followers": user_data.get("edge_followed_by", {}).get("count"),
"following": user_data.get("edge_follow", {}).get("count"),
"posts": user_data.get("edge_owner_to_timeline_media", {}).get("count"),
"is_private": user_data.get("is_private"),
"external_url": user_data.get("external_url")
}
return user_info
except requests.exceptions.RequestException as e:
logger.error(f"请求失败: {e}")
return None
except json.JSONDecodeError as e:
logger.error(f"JSON 解析失败: {e}")
return None


def main():
# 替换为您的 cookies(从浏览器开发者工具或抓包工具获取)
cookies = {
"datr": "qoUga1PC7Vb2xfx_Rectc8AW8",
"ig_did": "6D1BFA81E-9542-42D2-A005-93E591B49A9D",
"dpr": "1.3175",
"mid": "aCCFqg1ALAAFBWbRNhcq-dKkP7D0U",
"ig_nrcb": "1",
"ps_l": "1",
"ps_n": "1",
"csrftoken": "x1vD951m4mltz3Gwo7LGOmSVk2d2HfBqa1",
"ds_user_id": "743291869291",
"sessionid": "743291186929%3A7LWehUJrWsS1vE%3A20%3AAYeYxYpoNFx5MJAu7uo7dMfYLW-oQ8z9hi-FaaRkdw",
"wd": "1148x937",
"rur": "NHA\054743129186929\0541778498815:01f7ee4f72c0026e5643f7e964139a43e978e1a251d6919b7493a76293ac6c7bc8642abc"
}

# 请求头(模拟浏览器请求)
target_username = "jjlin" # 替换为您想爬取的用户名

headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
"x-ig-app-id": "9366197433924591", # Instagram 应用 ID(必要)
"x-csrftoken": "xvD951m4mltz3Gwo7LGOmSVk2d2HfBqa",
"accept": "application/json",
"referer": f"https://www.instagram.com/{target_username}/",
"x-ig-www-claim": "hmac.AR2-3v0n27y_xxxxxxxxxxxx", # 可选,替换为实际值或留空
}

# 目标用户名

# 获取用户信息
user_info = get_user_info(cookies, target_username, headers)

if user_info:
logger.info("用户信息:")
for key, value in user_info.items():
logger.info(f"{key}: {value}")


if __name__ == "__main__":
main()