UnicodeEncodeError: ‘latin-1‘ codec can‘t encode characters in position 问题

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' 

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇