【问题标题】:UnicodeEncodeError: 'charmap' codec can't encode character '\u2014' Python Beautiful SoupUnicodeEncodeError: 'charmap' codec can't encode character '\u2014' Python Beautiful Soup
【发布时间】:2017-05-10 15:33:30
【问题描述】:

这是我的代码:

soup = bs4.BeautifulSoup(res.text, "html.parser")
linkElems = soup.select('.r a')

for i in range(len(linkElems)):
    t = linkElems[i].findAll(text=True)
    print(t)

这给了我错误:

Traceback (most recent call last):
  File "C:\Path\Python\code.py", line 17, in <module>
     print(t)
  File "C:\Program Files\Python 3.5\lib\encodings\cp437.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_map)[0] 
UnicodeEncodeError: 'charmap' codec can't encode character '\u2014' in position 9: character maps to <undefined>

print(t) 行给了我错误。

我正在使用 Python 3 和 Beautiful Soup 4。我怎样才能摆脱这个错误?

【问题讨论】:

  • 顺便说一句,你可以在这里使用.get_text()[elm.get_text() for elm in soup.select('.r a')]
  • 总是显示有问题的完整错误消息(Traceback)。它显示了哪条线有问题。
  • 您可以添加指向源数据的链接。
  • 您在 unicode 中有文本,但 print() 始终必须将其转换为控制台/终端/cmd.exe/powershell 使用的编码 - 如果终端没有通知 python 它使用什么编码然后print() 对文本进行编码有问题。您可以手动编码文本,即。 print(t.encode('utf-8') but it may depend on system which you use - Linux mostly need utf-8` 但 Windows 可能需要 win1250 或其他。

标签: python python-3.x beautifulsoup python-3.5


【解决方案1】:

当您打开文件时,您使用的是编码 CP437,这在您的操作系统(您尚未指定)上是默认的。

当 CP437 检查文件时,它遇到一个无法编码的字符(第 2014 个 Unicode 字符,无论是十六进制还是十进制,您都没有指定)。

因此,它会出错,告诉您它无法对字符进行编码。

解决此问题的方法是将编码更改为 UTF-8,因为它可以解码所有 Unicode 字符,并且可能是文件真正编码的内容,因为 UTF-8 正在全球范围内使用。

要将其更改为 UTF-8,请使用以下代码:

soup = bs4.BeautifulSoup(res.text, "html.parser", from_encoding="utf-8")

这会将编码更改为 UTF-8(因为我添加了from_encoding="utf-8"),所以现在不是执行C:\Program Files\Python 3.5\lib\encodings\cp437.py 进行编码,而是执行C:\Program Files\Python 3.5\lib\encodings\utf8.py,它编码正确。

【讨论】:

    猜你喜欢
    • 2018-04-18
    • 2020-08-05
    • 2014-09-27
    • 2019-03-10
    • 2015-12-03
    • 1970-01-01
    • 1970-01-01
    • 2018-08-14
    • 2014-05-09
    相关资源
    最近更新 更多