【发布时间】:2019-09-25 04:23:25
【问题描述】:
我需要过滤一组相当长(但非常常规)的 .html 文件来修改一些结构只有如果它们出现在文本元素中。
一个很好的例子是将<p><div class="speech">it's hard to find his "good" side! He has <i>none</i>!<div></p> 更改为<p><div class="speech">it's hard to find his &ldquo;good&rdquo; side! He has <i>none</i>!<div></p>。
我可以使用html.parser 轻松解析我的文件,但不清楚如何生成结果文件,该文件应尽可能与输入相似(无需重新格式化)。
我看过 beautiful-soup,但对于这个(应该是?)简单的任务来说,它似乎太大了。
注意:我确实不需要/想要将 .html 文件提供给任何类型的浏览器;我只需要用(稍微)改变的内容更新它们(可能就地)。
更新:
按照@soundstripe 的建议,我编写了以下代码:
import bs4
from re import sub
def handle_html(html):
sp = bs4.BeautifulSoup(html, features='html.parser')
for e in list(sp.strings):
s = sub(r'"([^"]+)"', r'“\1”', e)
if s != e:
e.replace_with(s)
return str(sp).encode()
raw = b"""<p><div class="speech">it's hard to "find" his "good" side! He has <i>none</i>!<div></p>"""
new = handle_html(raw)
print(raw)
print(new)
不幸的是,BeautifulSoup 试图从它(和我)自己的利益出发变得过于聪明:
b'<p><div class="speech">it\'s hard to "find" his "good" side! He has <i>none</i>!<div></p>'
b'<p><div class="speech">it\'s hard to &ldquo;find&rdquo; his &ldquo;good&rdquo; side! He has <i>none</i>!<div></div></div></p>'
即:它将普通的&amp; 转换为&amp; 从而破坏&ldquo; 实体(注意我使用的是字节数组,而不是字符串。它相关吗?)。
我该如何解决这个问题?
【问题讨论】:
-
你可以使用 selenium webdriver
-
@Code_Ninja:乍一看,它看起来比漂亮的汤更有用。我错过了什么吗?
-
哈哈,不要害怕 API,selenium webdriver 为您提供了比 beautiful-soup 更多的功能,因为它的主要创建目的是在前端级别跟踪和自动化网站上的更改。跨度>