Python: file: encode: ‘gbk‘ codec can‘t encode character ‘\xe5‘ in position

错误

response = requests.get(url, timeout=5) # 请求一个网页

with open('response.txt', 'w') as file: # 打开一个文件

file.write(response.text) # 向文件写入response

提示错:

UnicodeEncodeError: 'gbk' codec can't encode character '\xe5' in position 520: illegal multibyte sequence

原因

这个是因为文件打开使用的编码方式是gbk,是open默认的,在response.text里有gbkencode不了的编码。导致错误。如果换成utf-8,倒是可以输出到文件:

with open('response.txt', 'w', encoding='utf-8') as file:

修改这一句,可以绕过这个错误,但是,打开网页出现乱码。

本地的默认设置是gbk。

cpp 复制代码
>>> import locale
>>> print(locale.getdefaultlocale())
('zh_CN', 'cp936')

Doc/library/codecs.rst

cpp 复制代码
| gbk             | 936, cp936, ms936              | Unified Chinese                |

从网上搜了一下,response自带编码方式,可以查阅。

cpp 复制代码
>>> print(response.encoding)
ISO-8859-1

最后改成ISO-8859-1就好了。

相关推荐
Austin_YB几秒前
VScode中配置Python环境
ide·vscode·python
qq_452396232 分钟前
【Python × AI】LangChain 深度剖析:从组件解耦到 LCEL 的逻辑美学
人工智能·python·ai·langchain
ChineHe2 分钟前
基础篇003_Python基础语法
开发语言·人工智能·python
oem1104 分钟前
Python Web爬虫入门:使用Requests和BeautifulSoup
jvm·数据库·python
CSDN_Colinw13 分钟前
Python GUI开发:Tkinter入门教程
jvm·数据库·python
沉沙丶18 分钟前
关于matlab分析电流THD的一些探究和记录
开发语言·matlab·电机控制·foc·永磁同步电机·模型预测·预测控制
chase。20 分钟前
Python包构建工具完全指南:python -m build 使用详解
开发语言·chrome·python
SuperEugene24 分钟前
前端 utils 工具函数规范:拆分 / 命名 / 复用全指南,避开全局污染等高频坑|编码语法规范篇
开发语言·前端·javascript
xin_yao_xin25 分钟前
PaddleOCR系列——《文本检测、文本识别》模型训练
人工智能·python·paddlepaddle·ppocr
2401_8331977325 分钟前
用Python制作一个文字冒险游戏
jvm·数据库·python