接口响应编码格式为带 BOM 头 utf-8. 直接获取响应的 text 出现乱码.
- '''
- dinghanhua
- 2018-11
- requests text 与 content, 指定响应的 encoding
- '''API ='http://testapi'
- response = requests.get(API)
- print(response.text)
乱码
解决方式:
1 获取 content 再用 utf-8-sig decode.
2 指定响应的编码格式为 utf-8-sig. 再获取 text.
1 指定 response 的编码格式为 utf-8-sig
- #utf-8-sig 解码
- response.encoding = 'utf-8-sig'
- print(response.text)
- print(response.JSON()) #直接转成 JSON
2 获取 content, 再 utf-8-sig 解码
print(response.content) #二进制
前 3 个字符就是 BOM 头
- import JSON
- r = response.content.decode('utf-8-sig')
- print(JSON.loads(r))
也可以去掉 BOM 头之后用 utf-8 解码
- # 去掉 bom 头 3 个字符
- r = response.content[3:].decode('utf-8')
- print(JSON.loads(r))
如果不去掉 BOM 头用 utf-8 解码, 但 JSON.loads() 会报错
- r = response.content.decode('utf-8')
- print(r.decode('utf-8'))
- print(JSON.loads(r.decode('utf-8')))
来源: http://www.bubuko.com/infodetail-2859864.html