繁体   English   中英

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

[英]Remove a tag using BeautifulSoup but keep its contents

目前我的代码执行如下操作:

soup = BeautifulSoup(value)

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

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

当前版本的BeautifulSoup库在Tag对象上有一个名为replaceWithChildren()的未记录方法。 所以,你可以这样做:

html = "<p>Good, <b>bad</b>, and <i>ug<b>l</b><u>y</u></i></p>"
invalid_tags = ['b', 'i', 'u']
soup = BeautifulSoup(html)
for tag in invalid_tags: 
    for match in soup.findAll(tag):
        match.replaceWithChildren()
print soup

看起来它的行为就像你想要的那样,并且是相当简单的代码(尽管它确实通过DOM进行了一些传递,但这可以很容易地进行优化。)

我使用的策略是将标签替换为其内容,如果它们是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>

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

虽然评论中已经有其他人提到了这一点,但我想我会发布一个完整的答案,展示如何使用Mozilla的Bleach。 就个人而言,我认为这比使用BeautifulSoup要好得多。

import bleach
html = "<b>Bad</b> <strong>Ugly</strong> <script>Evil()</script>"
clean = bleach.clean(html, tags=[], strip=True)
print clean # Should print: "Bad Ugly Evil()"

我有一个更简单的解决方案,但我不知道它是否有缺点。

更新:有一个缺点,请参阅Jesse Dhillon的评论。 另外,另一种解决方案是使用Mozilla的Bleach而不是BeautifulSoup。

from BeautifulSoup import BeautifulSoup

VALID_TAGS = ['div', 'p']

value = '<div><p>Hello <b>there</b> my friend!</p></div>'

soup = BeautifulSoup(value)

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

print soup.renderContents()

这也将根据需要打印<div><p>Hello there my friend!</p></div>

你可以使用soup.text

.text删除所有标记并连接所有文本。

在删除标签之前,您可能必须将标签的子项移动为标记父项的子项 - 这是您的意思吗?

如果是这样,那么,虽然在正确的位置插入内容是棘手的,这样的事情应该工作:

from BeautifulSoup import BeautifulSoup

VALID_TAGS = 'div', 'p'

value = '<div><p>Hello <b>there</b> my friend!</p></div>'

soup = BeautifulSoup(value)

for tag in soup.findAll(True):
    if tag.name not in VALID_TAGS:
        for i, x in enumerate(tag.parent.contents):
          if x == tag: break
        else:
          print "Can't find", tag, "in", tag.parent
          continue
        for r in reversed(tag.contents):
          tag.parent.insert(i, r)
        tag.extract()
print soup.renderContents()

使用示例值,根据需要打印<div><p>Hello there my friend!</p></div>

提议的答案似乎都不适合我的BeautifulSoup。 这是一个与BeautifulSoup 3.2.1一起使用的版本,并且在连接来自不同标签的内容时也插入空格而不是连接单词。

def strip_tags(html, whitelist=[]):
    """
    Strip all HTML tags except for a list of whitelisted tags.
    """
    soup = BeautifulSoup(html)

    for tag in soup.findAll(True):
        if tag.name not in whitelist:
            tag.append(' ')
            tag.replaceWithChildren()

    result = unicode(soup)

    # Clean up any repeated spaces and spaces like this: '<a>test </a> '
    result = re.sub(' +', ' ', result)
    result = re.sub(r' (<[^>]*> )', r'\1', result)
    return result.strip()

例:

strip_tags('<h2><a><span>test</span></a> testing</h2><p>again</p>', ['a'])
# result: u'<a>test</a> testing again'

使用展开。

展开将删除标签的多次出现之一并仍然保留内容。

例:

>> soup = BeautifulSoup('Hi. This is a <nobr> nobr </nobr>')
>> soup
<html><body><p>Hi. This is a <nobr> nobr </nobr></p></body></html>
>> soup.nobr.unwrap
<nobr></nobr>
>> soup
>> <html><body><p>Hi. This is a nobr </p></body></html>

这是更好的解决方案,没有任何麻烦和样板代码来过滤掉保留内容的标签。让我们说你要删除父标签中的任何子标签,只想保留内容/文本,你可以简单地做:

for p_tags in div_tags.find_all("p"):
    print(p_tags.get_text())

就是这样,您可以使用父标签中的所有br或ib标签免费获得干净的文本。

这是一个老问题,但只是说更好的方法。 首先,BeautifulSoup 3 *不再开发,所以你应该使用BeautifulSoup 4 *,所谓的bs4

此外,lxml只具有您需要的功能: Cleaner类具有属性remove_tags ,您可以将其设置为在内容被拉入父标记时将被删除的标记。

这是这个函数的python 3友好版本:

from bs4 import BeautifulSoup, NavigableString
invalidTags = ['br','b','font']
def stripTags(html, invalid_tags):
    soup = BeautifulSoup(html, "lxml")
    for tag in soup.findAll(True):
        if tag.name in invalid_tags:
            s = ""
            for c in tag.contents:
                if not isinstance(c, NavigableString):
                    c = stripTags(str(c), invalid_tags)
                s += str(c)
            tag.replaceWith(s)
    return soup

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM