Python 3.x Python请求:UnicodeEncodeError:';charmap';编解码器可以';t编码字符
我抓取了一个网页(名称在这里的代码中更改),如下所示:Python 3.x Python请求:UnicodeEncodeError:';charmap';编解码器可以';t编码字符,python-3.x,python-unicode,Python 3.x,Python Unicode,我抓取了一个网页(名称在这里的代码中更改),如下所示: import requests r = requests.get('https://www.samplewebpage.com') f = open ('filename', 'w') f.write(r.text) f.close() 然后我尝试将r.text写入一个文件,如下所示: import requests r = requests.get('https://www.samplewebpage.com') f = open
import requests
r = requests.get('https://www.samplewebpage.com')
f = open ('filename', 'w')
f.write(r.text)
f.close()
然后我尝试将r.text写入一个文件,如下所示:
import requests
r = requests.get('https://www.samplewebpage.com')
f = open ('filename', 'w')
f.write(r.text)
f.close()
我得到一个错误,如下所示:
UnicodeEncodeError: 'charmap' codec can't encode character '\u20b9' in position 158691: character maps to <undefined>
UnicodeEncodeError:“charmap”编解码器无法对158691位置的字符“\u20b9”进行编码:字符映射到
r、 编码显示UTF-8。如何解决上述问题
还尝试了以下方法:
-很少有其他随机网页,我能够运行代码没有任何错误的大多数。
-使用r.content.decode('utf-8','ignore')代替r.text,但错误与上述相同
我的环境/系统规范:
- Python 3.6.4
- Windows 8.1 Pro,64位
- 从中安装的默认空闲
- 在Atom中也尝试了脚本,但出现了相同的错误
谢谢请尝试显式指定文件的编码:
f = open ('filename', 'w', encoding='utf8')
f.write(r.text)
f.close()