【发布时间】:2015-08-30 11:05:41
【问题描述】:
我有一个 html 文件,如下所示:
...
<p>
<strong>This is </strong>
<strong>a lin</strong>
<strong>e which I want to </strong>
<strong>join.</strong>
</p>
<p>
2.
<strong>But do not </strong>
<strong>touch this</strong>
<em>Maybe some other tags as well.</em>
bla bla blah...
</p>
...
我需要的是,如果'p'块中的所有标签都是'strong',那么将它们组合成一行,即
<p>
<strong>This is a line which I want to join.</strong>
</p>
不接触另一个块,因为它包含其他东西。
有什么建议吗?我正在使用 lxml。
更新:
到目前为止我试过了:
for p in self.tree.xpath('//body/p'):
if p.tail is None: #no text before first element
children = p.getchildren()
for child in children:
if len(children)==1 or child.tag!='strong' or child.tail is not None:
break
else:
etree.strip_tags(p,'strong')
使用这些代码,我能够在所需部分剥离强标签,给出:
<p>
This is a line which I want to join.
</p>
所以现在我只需要一种方法将标签放回...
【问题讨论】:
-
第一个块应该是
<strong>This is </strong>等还是</strong>缺失? -
@Scott 感谢您的指出,是的,我错过了。将编辑我的问题。
-
@har07 请看我的更新。