我正在尝试使用 Python 读取大量 .htm
文件。为此,我使用以下方法:
HtmlFile = codecs.open(file, 'r')
text = BeautifulSoup(HtmlFile.read()).text
但是,这会导致以下错误:
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 411:
character maps to <undefined>
所以,我尝试使用 utf-8
进行编码,如下所示:
HtmlFile = codecs.open(file, 'r', encoding='utf-8')
text = BeautifulSoup(HtmlFile.read()).text
然后我得到了这个错误:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 4565:
invalid start byte
我尝试遵循 here 的建议,但没有帮助。任何帮助将不胜感激!
最佳答案
我做了一些研究,这是使用 CP1252 编码的 Microsoft 生成的文件的问题,但是有些内容没有正确获取。鉴于以下情况:
<meta http-equiv=Content-Type content="text/html; charset=windows-1252">
<meta name=Generator content="Microsoft Word 15 (filtered)">
在您的 html 文件中,这似乎更有可能。
根据这个answer ,如果您在该示例中使用 Latin-1 编码,它可能会有所帮助:
HtmlFile = codecs.open(file, 'r', encoding='latin-1')
text = BeautifulSoup(HtmlFile.read()).text
请告诉我这是否有效。请注意,Latin-1 并不具有 Microsoft 编码所具有的所有字符。
关于python - 使用 Python 读取 .htm 文件时的编码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53824656/