UnicodeEncodeError: ‘latin-1’ codec can’t encode characters in position 48-49: Body (‘搞事情’) is not valid Latin-1. Use body.encode(‘utf-8’) if you want to send it encoded in UTF-8

在使用python或者robot framework 引用 requests时,请求发生以下错误提示:UnicodeEncodeError: ‘latin-1’ codec can’t encode characters in position 48-49: Body (‘搞事情’) is not valid Latin-1. Use body.encode(‘utf-8’) if you want to send it encoded in UTF-8;

解决办法:

请求的报文包含有中文字符或者其他字符导致编码格式不支持,可以将请求体的编码格式改为‘UTF-8’
因为汉字无法Unicode编码
如:

import requests

url = 'www.baidu.com'
datas = '搞事情'
bytedatas = datas.encode('UTF-8')  #转换编码格式
res = requests.post(url, data=bytedatas, headers=headers)

另外在使用pymysql 时,没有定义编码格式,在数据库中 insert 插入汉字时也可能出现以上报错
解决方法如下:

import pymysql
db = pymysql.connect(host='116.0.0.1', port=3306, user='root', passwd='666', db='mysql', charset='utf8')
#在连接中 指定 charset='utf8' 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐