在Google Colab执行GET请求遇KeyError,本地运行正常
问题
我是编程新手,尝试在Google Colab运行以下代码获取TikTok账户信息:
import requests, datetime, hashlib, hmac, random, zlib, json session_id = "my_id" session = requests.Session() session.cookies.set("sessionid", session_id, domain=".tiktok.com") url = "https://www.tiktok.com/passport/web/account/info/" r = session.get(url) print (r) user_id = r.json()["data"]["user_id_str"] print (user_id)
在Colab中运行返回错误:
/usr/local/lib/python3.10/dist-packages/ipykernel/ipkernel.py:283: DeprecationWarning: `should_run_async` will not call `transform_cell` automatically in the future. Please pass the result to `transformed_cell` argument and any exception that happen during thetransform in `preprocessing_exc_tuple` in IPython 7.17 and above. <Response [200]> --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-19-6d746d6bbbb9> in <cell line: 14>() 12 print (r) 13 ---> 14 user_id = r.json()["data"]["user_id_str"] 15 print (user_id) KeyError: 'user_id_str'
但在本地机器上运行该代码可正常返回结果:
<Response [200]> 7048890068204110850
请问为何会出现这种差异,该如何解决?
原因与解决方案
差异原因
- Colab服务器的IP属于云服务商集群,TikTok的反爬机制会将这类IP识别为非人工访问,返回的JSON数据结构和本地正常请求不同,可能缺失
user_id_str字段,甚至返回验证页面或空数据。 - 本地请求使用的是日常上网的个人IP,属于TikTok判定的正常用户IP范围,因此能返回完整账户信息。
解决办法
添加浏览器请求头模拟正常访问
在发送GET请求时,补充User-Agent、Referer等浏览器常用请求头,让请求更接近真实用户行为:headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36", "Referer": "https://www.tiktok.com/" } r = session.get(url, headers=headers)查看Colab返回的完整JSON数据
先打印返回的全部JSON内容,确认TikTok实际返回的数据结构:print(json.dumps(r.json(), indent=2))根据实际返回的结构调整字段提取逻辑,如果返回了验证相关内容,Colab环境下手动处理验证码难度较高,需结合其他方案。
使用 residential 代理IP
给Colab的请求配置真实用户的代理IP,绕过TikTok的IP识别。可以使用付费的住宅代理,代码中添加代理参数:proxies = { "http": "http://your-proxy-ip:port", "https": "https://your-proxy-ip:port" } r = session.get(url, headers=headers, proxies=proxies)
内容的提问来源于stack exchange,提问作者QGunther
相关产品推荐
相关产品推荐

