【问题标题】:Removing HTML tags from a unicode string in Python从 Python 中的 unicode 字符串中删除 HTML 标签
【发布时间】:2011-03-14 13:17:14
【问题描述】:

我有一个强大的,我从一个 XML 文件中抓取,它包含一些 HTML 格式标记

(<b>, <i>, etc)

有没有一种快速简便的方法可以从文本中删除所有这些标签?

我试过了

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

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

【问题讨论】:

  • 请不要使用str作为变量名。
  • 马克,我不是,我只是为示例输入的

标签: python html string unicode replace


【解决方案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>

【讨论】:

    【解决方案2】:

    使用 lxml.html:

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

    这会剥离所有标签并将所有实体转换为其对应的字符。

    【讨论】:

    • 谢谢!我得到 AttributeError: 'module' object has no attribute 'html' 当我尝试这个时
    【解决方案3】:

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

    【讨论】:

    • 听起来他不想解析任何 html,只是将其全部剥离,这样他就剩下纯文本(有点像 innerHTML 函数)。
    • 斯蒂芬,你是对的。我不是在尝试解析字符串,我只是想删除 HTML 格式(我想完全删除 中的任何内容)
    • 糟糕,我指的是 innerText 属性,而不是“innerHTML 函数”
    • 如果没有更复杂的解析,您将无法“仅”删除 HTML 格式。对于一些简单的样本可能是可行的,但对于复杂的样本则不是。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-24
    • 2021-02-05
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多