python - 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 实体是乱码显示的。
显然,我没有正确处理这个问题。有什么建议吗?
解决方案
保存文件时有一种更聪明的方法:
with open(file, "w", encoding="ascii") as f:
f.write(str(parser.encode('ascii').decode()))
推荐阅读
- dynamics-crm - 在 Dynamics-365 中创建报价时出现“缺少 prvCreatemsdyn_quotepricelist 特权”错误
- hive - 如何从某个位置读取表并将数据写入其他集群的表
- bash - 从s3存储桶下载时如何设置水印
- angular - 为什么这个 ASP.NET Core Web 应用程序不能从 D: Drive 运行?
- java - Java:关于字符串的初学者问题
- csv - 无法将 Influxdb 导出到 CSV 文件中
- asp.net-core - Websocket 连接到“wss://mydomain/hub”失败:WebSocket 握手期间出错:意外响应代码:200
- asp.net - 调用 ASP.NET Web API 2 时重定向过多
- spring-cloud-config - spring cloud config是否支持集中证书?
- kubernetes - kubeadm join 命令加入 HA k8s master 集群失败