Python requests 库中 'UnicodeEncodeError: 'latin-1' codec can't encode characters' 错误解决方法

当使用 Python requests 库访问 QQ 空间 API 时,可能会遇到以下错误:

import requests

url = 'https://users.qzone.qq.com/fcg-bin/cgi_get_portrait.fcg?uins=19319429'
response = requests.get(url)
response.encoding = 'utf-8'  # 设置编码为utf-8
data = response.text.encode('latin1').decode('unicode_escape')
print(data)

上述代码运行报错显示:

Traceback (most recent call last):
  File "C:\Users\YeQingYu\PycharmProjects\pythonProject1\叶倾羽网络\请求api项目\qqname.py", line 6, in <module>
    data = response.text.encode('latin1').decode('unicode_escape')
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 99-103: ordinal not in range(256)

这个错误是由于尝试使用 'latin-1' 编码对包含非 'latin-1' 字符的数据进行编码导致的。为了解决这个问题,可以尝试使用其他编码方式,比如 'utf-8'。

修改代码如下:

import requests

url = 'https://users.qzone.qq.com/fcg-bin/cgi_get_portrait.fcg?uins=19319429'
response = requests.get(url)
response.encoding = 'utf-8'  # 设置编码为utf-8
data = response.text.encode('utf-8').decode('unicode_escape')
print(data)

这样就使用 'utf-8' 编码对数据进行编码,然后再使用 'unicode_escape' 进行解码,从而避免了 'UnicodeEncodeError' 错误。

Python requests库中UnicodeEncodeError: 'latin-1' codec can't encode characters 错误解决方法

原文地址: http://www.cveoy.top/t/topic/o4vN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录