使用BeautifulSoup删除标签,但保留其内容


问题内容

目前,我有执行以下操作的代码:

soup = BeautifulSoup(value)

for tag in soup.findAll(True):
    if tag.name not in VALID_TAGS:
        tag.extract()
soup.renderContents()

除非我不想丢弃无效标签内的内容。如何在调用soup.renderContents()时删除标记,但将内容保留在里面?


问题答案:

我使用的策略是用标签的内容替换标签,如果它们是类型的NavigableString,如果不是,则递归到标签中,并用替换标签的内容NavigableString,等等。

from BeautifulSoup import BeautifulSoup, NavigableString

def strip_tags(html, invalid_tags):
    soup = BeautifulSoup(html)

    for tag in soup.findAll(True):
        if tag.name in invalid_tags:
            s = ""

            for c in tag.contents:
                if not isinstance(c, NavigableString):
                    c = strip_tags(unicode(c), invalid_tags)
                s += unicode(c)

            tag.replaceWith(s)

    return soup

html = "<p>Good, <b>bad</b>, and <i>ug<b>l</b><u>y</u></i></p>"
invalid_tags = ['b', 'i', 'u']
print strip_tags(html, invalid_tags)

结果是:

<p>Good, bad, and ugly</p>

我在另一个问题上也给出了相同的答案。似乎很多。