UnicodeEncodeError:'charmap'编解码器无法编码字符
我想刮一个网站,但它给了我一个错误。UnicodeEncodeError:'charmap'编解码器无法编码字符
我用下面的代码:
import urllib.request
from bs4 import BeautifulSoup
get = urllib.request.urlopen("https://www.website.com/")
html = get.read()
soup = BeautifulSoup(html)
print(soup)
而且我发现了以下错误:
File "C:\Python34\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 70924-70950: character maps to <undefined>
我能做些什么来解决这个问题?
我通过将.encode("utf-8")
加到soup
来修复它。
这意味着print(soup)
变为print(soup.encode("utf-8"))
。
对于仍然出现此错误的人,将encode("ascii")
添加到soup
也会解决此问题。
soup = BeautifulSoup(html_doc, 'html.parser').encode("ascii")
print(soup)
刮保存网页内容到一个文件时,我得到了相同的UnicodeEncodeError
。要解决它,我更换验证码:
with open(fname, "w") as f:
f.write(html)
与此:
import io
with io.open(fname, "w", encoding="utf-8") as f:
f.write(html)
使用io
为您提供向后兼容性与Python 2.如果你只需要支持Python 3中,你可以使用内置open
功能代替。
在mac(python 3)完美地工作,只是打开没有编码,但在Windows(w10,python3)不是一个选项。只要以这种方式工作,encoding =“utf-8”参数。 – xtornasol512 2017-04-30 01:14:03
谢谢。它为我工作,我正在处理XML文件,并在新文件中写入xml.toprettyxml()的结果 – 2018-01-16 17:06:24
请勿在您的脚本中硬编码您的环境的字符编码(例如,控制台),[直接打印Unicode](http://stackoverflow.com/a/32176732/4279) – jfs 2015-09-07 04:09:59
这只是打印repr一个'bytes'对象,如果有很多UTF-8编码的文本,它将打印成'\ x'序列的混乱。正如@ J.F.Sebastian所建议的,我建议使用'win_unicode_console'。 – eryksun 2016-05-23 20:48:01
我使用了上面的解决方案,但sill得到了问题:class MyStreamListener(tweepy.StreamListener): def on_status(self,status): print(str(status.encode(“utf-8”))) UnicodeEncodeError:'charmap '编解码器不能编码字符'\ u2019'在位置87:字符映射到 –
Vivek
2016-09-26 23:49:28