【发布时间】:2019-01-23 08:47:47
【问题描述】:
我正在编写一些 HTML 预处理脚本,这些脚本从网络爬虫中清理/标记 HTML,用于随后的语义/链接分析步骤。我已从 HTML 中过滤掉不需要的标签,并将其简化为仅包含可见文本和 <div> / <a> 元素。
我现在正在尝试编写一个“collapseDOM()”函数来遍历 DOM 树并执行以下操作:
(1) 销毁没有任何可见文本的叶子节点
(2) 折叠任何<div>,并将其替换为其子级,如果它 (a) 直接不包含可见文本并且 (b) 只有一个 <div> 子级
例如,如果我有以下 HTML 作为输入:
<html>
<body>
<div>
<div>
<a href="www.foo.com">not collapsed into empty parent: only divs</a>
</div>
</div>
<div>
<div>
<div>
inner div not collapsed because this contains text
<div>some more text ...</div>
but the outer nested divs do get collapsed
</div>
</div>
</div>
<div>
<div>This won't be collapsed into parent because </div>
<div>there are two children ...</div>
</div>
</body>
它应该变成这个“折叠”的版本:
<html>
<body>
<div>
<a href="www.foo.com">not collapsed into empty parent: only divs</a>
</div>
<div>
inner div not collapsed because this contains text
<div>some more text ...</div>
but the outer nested divs do get collapsed
</div>
<div>
<div>This won't be collapsed into parent because </div>
<div>there are two children ...</div>
</div>
</body>
我一直无法弄清楚如何做到这一点。我尝试使用 BeautifulSoup 的 unwrap() 和 decompose() 方法编写递归树遍历函数,但这在迭代它时修改了 DOM,我无法弄清楚如何让它工作......
有没有一种简单的方法来做我想做的事?我对 BeautifulSoup 或 lxml 中的解决方案持开放态度。谢谢!
【问题讨论】:
标签: html dom merge beautifulsoup lxml