Python去除标签

8 投票
9 回答
10394 浏览
提问于 2025-04-15 21:17

我想要实现以下功能。

input : this is test <b> bold text </b> normal text
expected output: this is test normal text

也就是说,删除指定标签中的内容。

9 个回答

5

如果你不介意使用Python(虽然正则表达式是比较通用的),你可以参考一下Django的strip_tags过滤器

这里为了完整性再复制一遍 -

def strip_tags(value):
    """Returns the given HTML with all tags stripped."""
    return re.sub(r'<[^>]*?>', '', force_unicode(value))

补充说明:如果你在使用这个,或者其他任何正则表达式的解决方案,请记住,它可能会放过一些精心制作的HTML(见评论),还有HTML注释,因此不应该用在不可信的输入上。建议使用beautifulsoup、html5lib或lxml等库来处理不可信的输入。

5

使用BeautifulSoup:

from BeautifulSoup import BeautifulSoup    
''.join(BeautifulSoup(page).findAll(text=True))

可以在这里找到:http://www.ghastlyfop.com/blog/2008/12/strip-html-tags-from-string-python.html

9

使用 BeautifulSoup 的解决方案:

from BeautifulSoup import BeautifulSoup
def removeTag(soup, tagname):
    for tag in soup.findAll(tagname):
        contents = tag.contents
        parent = tag.parent
        tag.extract()

s = BeautifulSoup("abcd <b> btag </b> hello <d>dtag</d>")

removeTag(s,"b")
print s
removeTag(s, "d")
print s

返回结果:

>>>
abcd  hello <d>dtag</d>
abcd  hello

撰写回答