为什么我会收到“UnicodeEncodeError:'charmap'编解码器无法在位置84811编码字符'\u25b2':字符映射到<undefined>”错误提示?

16

当运行以下代码时,我遇到了UnicodeEncodeError: 'charmap' codec can't encode character '\u200b' in position 756: character maps to 的错误:

from bs4 import BeautifulSoup
import requests
r = requests.get('https://stackoverflow.com').text
soup = BeautifulSoup(r, 'lxml')
print(soup.prettify())

输出结果为:

Traceback (most recent call last):
  File "c:\Users\Asus\Documents\Hello World\Web Scraping\st.py", line 5, in <module>
    print(soup.prettify())
  File "C:\Users\Asus\AppData\Local\Programs\Python\Python38\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u200b' in position 756: character maps to <undefined>

我正在使用Python 3.8.1和UTF-8编码在VS Code中。如何解决这个问题?


这个回答解决了你的问题吗?UnicodeEncodeError:'charmap'编解码器无法编码字符 - Ulrich Eckhardt
3个回答

18
完整的错误信息中有一些提示...我会保留最重要的部分在这里:

提示 1

提示 2

提示 3

Traceback ...
  File "...\cp1252.py", ...
UnicodeEncodeError: 'charmap' codec can't encode character '\u200b' ...

错误是由print调用引起的。你的文本中某处有一个零宽度空格字符(Unicode U+200B),如果你在Windows控制台上打印,该字符串会被内部编码为Windows控制台代码页(这里是cp1252)。而零宽度空格在该代码页中无法表示。顺便说一句,在Windows中,默认控制台并不真正支持Unicode。
在Windows控制台中没有太多可以做的。我建议你尝试以下其中一种解决方法:
  • do not print to the console but write to a (utf8) file. You will then be able to read it with a utf8 enabled text editor like notepad++

  • manually encode anything before printing it, with errors='ignore' or errors='replace'. That way, possibly offending characters will be ignored and no error will arise

      print(soup.prettify().encode('cp1252', errors='ignore'))
    

16

您可以自己稍微探索一下...但对于Python 2.7,我通常使用以下方法来清理我的文本:

text = text.encode('utf-8').decode('ascii', 'ignore')

Python 3 的等价写法是:

text = str(text)

针对您的情况,请尝试以下方法:

r = requests.get('https://stackoverflow.com').text.encode('utf8').decode('ascii', 'ignore')

否则通常情况下:

r = requests.get('https://stackoverflow.com')
soup = BeautifulSoup(r.content, 'lxml')
print soup

(我认为这不应该产生任何错误。)


你是说将soup转换为字符串,然后使用prettify吗? - Asir Shahriar Roudra
兄弟,运行你的代码时出现了一个新错误,我得到了以下输出:Traceback (most recent call last): File "c:\Users\Asus\Documents\Hello World\Web Scraping\reddit.py", line 6, in print(soup) File "C:\Users\Asus\AppData\Local\Programs\Python\Python38\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' 编解码器不能在位置734处编码字符 '\u200b',因为该字符映射到 - Asir Shahriar Roudra

9

对于 Python 3,您可以使用以下代码:

text = str(text.encode('utf-8'))

谢谢!这个解决方案对我有用。首先,我尝试了Vaibhab的解决方案。然而,它没有起作用。 - rafaoc
对于错误“UnicodeEncodeError: 'charmap' codec can't encode character '\u021d'”,以下代码适用于我:df[file] = pd.read_csv(data_path+file, encoding="ISO-8859-1") #如果utf-8编码错误 print(str(file.encode('utf-8')))print('{0}已成功创建'.format(str(tbl_name.encode('utf-8')))) - Lod

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接