错误
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就好了。