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

Python调用API遇特殊字符编码错误,求解决方案

解决方案:处理API请求中的特殊字符编码问题

问题根源

你的错误本质是Windows终端默认编码(CP1252)不支持UTF-8中的特殊字符,不管是用subprocess调用curl还是直接用requests,最终在输出(print)时触发了编码转换失败。


1. 修复subprocess调用curl的问题

原代码用text=True时,Python会用系统默认编码(CP1252)解码curl的输出,而curl返回的是UTF-8编码的内容,导致解码错误。只需显式指定encoding='utf-8':

command = "https://api.scryfall.com/cards/search?q=unique%3Aprints%20e%3ALTR%20%21%22Rosie%20Cotton%20of%20South%20Lane%22"
completed_process = subprocess.run(['curl', '-s', command], capture_output=True, text=True, encoding='utf-8', timeout=5)
# 后续可正常处理输出
print(completed_process.stdout)

2. 修复requests的输出问题

requests已经正确将响应解码为Unicode字符串(从你打印的ENCODING: utf-8可确认),错误出在print到Windows终端的环节。有三种解决方式:

方式一:临时切换终端编码为UTF-8

  • Git Bash中执行:
    export PYTHONIOENCODING=utf-8
    
  • CMD中执行:
    chcp 65001
    

之后再运行Python脚本,即可正常打印特殊字符。

方式二:在Python代码中强制设置标准输出编码

在脚本开头添加以下代码,强制让sys.stdout使用UTF-8编码:

import sys
sys.stdout.reconfigure(encoding='utf-8')

# 后续正常使用requests
import requests
command = "https://api.scryfall.com/cards/search?q=unique%3Aprints%20e%3ALTR%20%21%22Rosie%20Cotton%20of%20South%20Lane%22"
apiRes = requests.get(command)
print(apiRes.json())  # 或 print(apiRes.text)

方式三:跳过终端输出,直接写入UTF-8文件

如果不需要在终端查看结果,直接将内容写入UTF-8编码的文件:

import requests
command = "https://api.scryfall.com/cards/search?q=unique%3Aprints%20e%3ALTR%20%21%22Rosie%20Cotton%20of%20South%20Lane%22"
apiRes = requests.get(command)

# 写入文本格式
with open('response.txt', 'w', encoding='utf-8') as f:
    f.write(apiRes.text)

# 或写入格式化的JSON
import json
with open('response.json', 'w', encoding='utf-8') as f:
    json.dump(apiRes.json(), f, ensure_ascii=False, indent=2)

最佳实践

推荐直接使用requests库(而非subprocess调用curl),它更适配Python的HTTP请求场景,编码处理更可控。结合终端编码切换或代码中设置标准输出编码,即可完美解决特殊字符问题。

内容的提问来源于stack exchange,提问作者Tiera.3

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 11:00:24