python - 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
解决方案
有多种方法可以处理具有未知编码的文本数据。然而在这种情况下,当您打算将数据传递给 Beautiful Soup 时,解决方案很简单:不要费心尝试自己解码文件,让 Beautiful Soup 来做。Beautiful Soup 会自动将字节解码为 unicode。
在您当前的代码中,您以文本模式读取文件,这意味着 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'
推荐阅读
- windows - 使用外部清单关闭 Windows DPI 缩放
- deployment - 跟踪配置表中的更改并创建自动化脚本以将它们部署到其他环境
- loops - python数据框中的嵌套循环
- node.js - nodejs删除路由警告/确认
- python-3.x - SyntaxError:行继续字符重新后的意外字符
- javascript - 从html开始,一次缩小js和css
- android - 如何通过对象动画师为drawable设置动画
- python - balebot 付款消息中的错误
- android - 如果应用程序关闭,如何将自定义数据从 FCM 保存到本地数据库?
- heroku - 如何根据生产过程中heroku提供的数据库凭据更改数据库名称?