Python无法解码交易账户Web请求(返回状态码200)
解决请求返回200但Python无法解码的问题
嘿,我之前也碰到过一模一样的情况——请求明明返回200成功,但就是没法正常解码响应内容!结合你给出的代码,咱们一步步来排查和解决:
可能的原因&对应解决方案
1. 压缩内容未被正确解压
你在请求头里设置了accept-encoding: gzip, deflate, br,服务器很大概率返回了压缩后的响应。虽然requests库通常会自动处理解压,但偶尔会出现异常情况。
解决办法:
- 最简单的方式:移除这个请求头,让服务器返回未压缩的内容:
headers = { 'accept-language': 'en-US,en;q=0.9', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36', 'x-kite-version': '1.2.1', 'accept': 'application/json, text/plain, */*', 'referer': 'https://ki...' } # 去掉accept-encoding头,避免服务器返回压缩内容
- 如果必须保留压缩头,可以手动解压响应:
import gzip from io import BytesIO response = requests.get("你的交易API地址", headers=headers) if response.headers.get('Content-Encoding') == 'gzip': buffer = BytesIO(response.content) with gzip.GzipFile(fileobj=buffer) as f: decoded_content = f.read().decode('utf-8')
2. 响应编码不匹配
服务器返回的内容编码可能和requests自动检测的编码不一致,直接导致解码失败。
解决办法:
先打印响应的基础信息,确认实际情况:
response = requests.get("你的API地址", headers=headers) print("响应编码:", response.encoding) print("内容类型:", response.headers.get('Content-Type')) # 打印前100字节的原始内容,快速判断是否是乱码或非预期格式 print("原始内容片段:", response.content[:100])
如果自动检测的编码不对,手动指定编码解码:
# 强制用utf-8解码,这是最常见的编码格式 decoded_text = response.content.decode('utf-8') # 如果有无法解码的特殊字符,可忽略错误继续解码 decoded_text = response.content.decode('utf-8', errors='ignore')
3. 响应并非预期的JSON格式
虽然你在请求头里指定了accept: application/json,但服务器可能返回了其他内容(比如登录页面、HTML提示页)——尤其是如果你的请求缺少认证信息(比如有效cookie、token)时,即使返回200,也可能是未授权的跳转页面。
解决办法:
先验证响应是否真的是JSON:
try: # 尝试解析JSON data = response.json() print("解析后的JSON数据:", data) except ValueError: # 解析失败,打印文本内容确认是什么 print("响应不是JSON格式,内容片段:", response.text[:500])
如果发现是未授权页面,你需要先完成登录流程,携带有效的认证信息(比如cookie、Authorization头)再发起请求。
完整调试代码示例
import requests headers = { 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'en-US,en;q=0.9', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36', 'x-kite-version': '1.2.1', 'accept': 'application/json, text/plain, */*', 'referer': 'https://ki...' } response = requests.get("你的交易账户API地址", headers=headers) # 基础信息排查 print("状态码:", response.status_code) print("内容编码:", response.encoding) print("内容类型:", response.headers.get('Content-Type')) # 尝试解码 try: # 先试试自动解码 text = response.text print("自动解码内容片段:", text[:200]) except UnicodeDecodeError: # 手动指定utf-8解码 text = response.content.decode('utf-8', errors='ignore') print("手动解码内容片段:", text[:200]) # 尝试解析JSON try: data = response.json() print("解析后的JSON数据:", data) except ValueError: print("无法解析为JSON,响应可能是非预期格式")
内容的提问来源于stack exchange,提问作者dnyanesh ambhore
相关产品推荐
相关产品推荐

