在Python中从unicode字符串中移除HTML标签

3 投票
3 回答
1884 浏览
提问于 2025-04-16 01:08

我从一个XML文件中提取了一些内容,这些内容里面有一些HTML格式的标签。

(<b>, <i>, etc)

有没有简单快捷的方法可以把这些标签都去掉呢?

我试过

str = str.replace("<b>","")

并且对其他标签也用过几次,但效果不好。

3 个回答

1

这个回答要看你具体的需求。如果你想的话,可以看看正则表达式。不过我建议你使用http://www.crummy.com/software/BeautifulSoup/,如果你想处理一些格式不太好的xml或html文件的话,这个工具会很有帮助。

1

下面是如何使用BeautifulSoup模块来替换一些标签,而不改变其他HTML内容的方法:

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 type(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>
6

使用 lxml.html:

lxml.html.fromstring(s).text_content()

这个方法会去掉所有的标签,并把所有的实体转换成对应的字符。

撰写回答