首页 > 解决方案 > UnicodeDecodeError 'utf-8' codec can't decode byte 0x92 in position 2893: invalid start byte

问题描述

我正在尝试打开一系列 HTML 文件,以便使用 BeautifulSoup 从这些文件的正文中获取文本。我有大约 435 个文件要运行,但我不断收到此错误。

我尝试将 HTML 文件转换为文本并打开文本文件,但我得到了同样的错误......

path = "./Bitcoin"
for file in os.listdir(path):
    with open(os.path.join(path, file), "r") as fname:
        txt = fname.read()

我想获取 HTML 文件的源代码,以便可以使用 beautifulsoup 对其进行解析,但出现此错误

---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
<ipython-input-133-f32d00599677> in <module>
      3 for file in os.listdir(path):
      4     with open(os.path.join(path, file), "r") as fname:
----> 5         txt = fname.read()

~/anaconda3/lib/python3.7/codecs.py in decode(self, input, final)
    320         # decode input (taking the buffer into account)
    321         data = self.buffer + input
--> 322         (result, consumed) = self._buffer_decode(data, self.errors, final)
    323         # keep undecoded input until the next call
    324         self.buffer = data[consumed:]

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x92 in position 2893: invalid start byte

标签: pythoncharacter-encoding

解决方案


有多种方法可以处理具有未知编码的文本数据。然而在这种情况下,当您打算将数据传递给 Beautiful Soup 时,解决方案很简单:不要费心尝试自己解码文件,让 Beautiful Soup 来做。Beautiful Soup 会自动将字节解码为 un​​icode

在您当前的代码中,您以文本模式读取文件,这意味着 Python 将假定文件被编码为 UTF-8,除非您为open函数提供编码参数。如果文件的内容不是有效的 UTF-8,这会导致错误。

for file in os.listdir(path):
    with open(os.path.join(path, file), "r") as fname:
        txt = fname.read()

相反,以二进制模式读取 html 文件并将生成的bytes实例传递给 Beautiful Soup。

for file in os.listdir(path):
    with open(os.path.join(path, file), "rb") as fname:
        bytes_ = fname.read()
soup = BeautifulSoup(bytes_)

FWIW,当前导致您的问题的文件可能使用 cp1252 或类似的 windows 8 位编码进行编码。

>>> '’'.encode('cp1252')
b'\x92'

推荐阅读