python - 使用 Python 读取 .htm 文件时的编码问题

标签 python html beautifulsoup

我正在尝试使用 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/

相关文章:

html - Wordpress 如何使 slider 全宽(Metaslider)

javascript - 在具有不同类的相同元素上使用淡入淡出

python - 使用 beautifulsoup 抓取 <h2> 标签

python - 使用 Beautiful Soup 的 Python 网络爬虫 BFS 算法?

python - 使用对数轴时如何显示 0 长度条的标签

python - pyplot 轴中的日期时间格式

html - 将表格行显示为列表

python - chartink.com 网页的网络抓取

python - 没有时间的python中的tail -f.sleep

python - 将 pyenv python 链接到 homebrew 以避免安装 homebrew python@3.8