首页 > 解决方案 > BeautifulSoup: html-encode 特殊字符

问题描述

我正在尝试使用 BeautifulSoup 对 HTML 文件中的标题和 p 元素中的所有文本进行 html 编码。

parser = BeautifulSoup('file.html', "html.parser")
pars = parser.find_all(['p', 'h1', 'h2', 'h3'])
for p in pars:
    if p.string != None:
        p.string = p.string.encode('ascii', 'xmlcharrefreplace')

这会产生以下错误:AttributeError: 'bytes' object has no attribute 'parent'. 所以我发现encode返回一个byte对象。如果我然后用 ASCII 解码它:

p.string = p.string.encode('ascii', 'xmlcharrefreplace').decode('ascii')

我没有同样的错误,但在某些情况下,HTML 实体是乱码显示的。

显然,我没有正确处理这个问题。有什么建议吗?

标签: pythonhtmlbeautifulsoup

解决方案


保存文件时有一种更聪明的方法:

with open(file, "w", encoding="ascii") as f:
    f.write(str(parser.encode('ascii').decode()))

推荐阅读