从Python中的unicode字符串中删除HTML标记

时间:2010-07-11 19:31:34

标签: python html string unicode replace

我很强大,我从XML文件中删除了它,它包含一些HTML格式标记

(<b>, <i>, etc)

是否有快速简便的方法从文本中删除所有这些标签?

我试过

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

并将其多次应用于其他标签,但这不起作用

3 个答案:

答案 0 :(得分:5)

使用lxml.html:

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

这会删除所有标记并将所有实体转换为相应的字符。

答案 1 :(得分:1)

答案取决于您的确切需求。您可以查看正则表达式。但是如果你想要清理坏的xml或html,我会建议你使用http://www.crummy.com/software/BeautifulSoup/

答案 2 :(得分: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>