我正在尝试打开一系列 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
有多种方法可以处理具有未知编码的文本数据。然而,在这种情况下,当您打算将数据传递给 Beautiful Soup 时,解决方案很简单:不必费心尝试自己解码文件,让 Beautiful Soup 来完成。美丽的汤会自动将字节解码为 unicode https://www.crummy.com/software/BeautifulSoup/bs4/doc/#encodings.
在当前代码中,您以文本模式读取文件,这意味着 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
以美丽汤为例。
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'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)