抓取用户粉丝量(哔哩哔哩平台)
import requests
import time
TARGET_MID = "163637592"
INTERVAL = 10 # 请求间隔(秒)
完善的请求头(模拟真实浏览器)
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36 Edg/144.0.0.0",
"Referer": f"https://space.bilibili.com/{TARGET_MID}",
"Cookie": "" # 可选:如果还是报错,可复制浏览器的B站Cookie(注意隐私)
}
while True:
try:
# 正确的粉丝数接口(B站的“空间统计”接口)
url = f"https://api.bilibili.com/x/relation/stat?vmid={TARGET_MID}"
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
data = response.json()
if data["code"] == 0:
follower = data["data"]["follower"] # 这个接口的follower是真实粉丝数
current_time = time.strftime("%Y-%m-%d %H:%M:%S")
print(f"[{current_time}] 用户 {TARGET_MID} 粉丝数:{follower}")
else:
print(f"请求失败,错误码:{data['code']},信息:{data.get('message', '无')}")
except requests.exceptions.RequestException as e:
print(f"请求错误:{str(e)}")
except KeyError as e:
print(f"数据解析错误(接口字段可能变化):缺少字段 {e}")
except Exception as e:
print(f"其他错误:{str(e)}")
time.sleep(INTERVAL)

浙公网安备 33010602011771号