使用python lxml将多个<br/>标签合并到一个标签

时间:2013-12-26 04:18:13

标签: python lxml

我有一个python脚本来清理已删除的HTML内容,它使用BeautifulSoup4并且效果很好。最近我决定学习lxml,但我发现教程更难(对我而言)。例如,我使用以下代码将多个<br />标记合并为一个,即,如果有多个<br />标记,请删除所有标记但只保留一个:

from bs4 import BeautifulSoup, Tag
data = 'foo<br /><br>bar. <p>foo<br/><br id="1"><br/>bar'
soup = BeautifulSoup(data)
for br in soup.find_all("br"):
    while isinstance(br.next_sibling, Tag) and br.next_sibling.name == 'br':
        br.next_sibling.extract()
print soup
<html><body><p>foo<br/>bar. </p><p>foo<br/>bar</p></body></html>

如何在lxml中实现此类似功能?谢谢,

1 个答案:

答案 0 :(得分:3)

您可以尝试.drop_tag()方法删除<br/>标记的重复连续出现次数:

from lxml import html

doc = html.fromstring(data)
for br in doc.findall('.//br'):
    if br.tail is None: # no text immediately after <br> tag
        for dup in br.itersiblings():
            if dup.tag != 'br': # don't merge if there is another tag inbetween
                break
            dup.drop_tag()
            if dup.tail is not None: # don't merge if there is a text inbetween
               break

print(html.tostring(doc))
# -> <div><p>foo<br>bar. </p><p>foo<br>bar</p></div>