【问题标题】:Safely remove all html code from a string in python从 python 中的字符串中安全地删除所有 html 代码
【发布时间】:2013-03-31 06:15:58
【问题描述】:

我已经阅读了很多关于如何使用 python 从字符串中删除所有 html 代码的问答,但没有一个令人满意。我需要一种方法来删除所有标签,保留/转换 html 实体并与 utf-8 字符串一起工作。

显然 BeautifulSoup 容易受到一些特制的 html 字符串的攻击,我用 HTMLParser 构建了一个简单的解析器来获取文本,但我丢失了实体

from HTMLParser import HTMLParser

class MyHTMLParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.data = []

    def handle_data(self, data):
        self.data.append(data)

    def handle_charref(self, name):
        self.data.append(name)

    def handle_entityref(self, ent):
        self.data.append(ent)

给了我类似的东西

[u'Asia, sp', u'cialiste du voyage', ...

在 spécialiste 中丢失重音“e”的实体。

使用您可以找到的众多正则表达式之一作为类似问题的答案,它总会有一些未被考虑的边缘情况。

有什么好的模块可以用吗?

【问题讨论】:

    标签: python html security parsing utf-8


    【解决方案1】:

    bleach 非常适合这项任务。它可以满足您的一切需求。它有一个广泛的测试套件,可以检查标签可能漏掉的奇怪边缘情况。我从来没有遇到过问题。

    【讨论】:

    • bleach.clean('is not allowed', strip=True) 这可能正是我需要的,我会用 utf-8、html 实体做一些测试今晚的东西,然后让你知道,谢谢
    • Bleach 可能无法将 HTML 实体转换为它们真正的 UTF-8 对应物。如果没有,试试这个问题:stackoverflow.com/questions/57708/…
    【解决方案2】:

    也许是 pyquery?尝试easy_install / pip install pyquery;然后是一些代码:

    from pyquery import PyQuery as jQ
    
    dom = jQ("<html>...</html>")
    print dom("body").text() 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-28
      • 1970-01-01
      • 2011-07-12
      • 1970-01-01
      • 1970-01-01
      • 2014-04-26
      相关资源
      最近更新 更多