【问题标题】:How to do HTML escaping in Python? [duplicate]如何在 Python 中进行 HTML 转义? [复制]
【发布时间】:2014-01-21 23:29:12
【问题描述】:

我正在尝试实现一个替换以下值的函数:

# > with >
# < with &lt;
# " with &quot;
# & with &amp

我的函数不断出错。到底有什么问题?

def escape_html(s):
    data = list(s)
    if ">" in data:
        data.replace(">","&gt;") 
    if "<" in data:
        data.replace("<","&lt;") 
    if '"' in data:
        data.replace('"',"&quot;") 
    if "&" in data:
        data.replace("&","&amp;") 
    word = data.join()
    return word

print escape_html("<>")

注意:这更像是一个基本的编程问题。我的重点是我的功能不起作用的原因。我不能为这个项目使用外部库。

【问题讨论】:

标签: python string


【解决方案1】:

使用cgi.escape:

>>> import cgi
>>> cgi.escape('<this & that>')
'&lt;this &amp; that&gt;'

如果您使用 Python 3.2+,请按照文档建议使用 html.escape

cgi.escape

自版本 3.2 后已弃用:此函数不安全,因为 quote 默认为 false,因此已弃用。请改用html.escape()

【讨论】:

  • 您能否举个例子,quote 有所作为?
  • @MartinThoma, cgi.escape('"') 返回'"'html.escape('"') 返回'&amp;quot;'
【解决方案2】:

有内置函数可以做到这一点。如果您使用的是 Python 2.x,则可以使用 cgi.escape。它在 Python 3.2 中已弃用。所以,如果你使用 Python >= 3.2,你可以使用html.escape

【讨论】:

    【解决方案3】:

    你也可以使用replace,它更通用一点。

    例如,

    string = ">>>"
    new_string = string.replace(">", "&gt;")
    print new_string # '&gt;&gt;&gt;'
    

    但是,请记住,如果您尝试替换双引号,则需要将它们括在单引号中,反之亦然

    【讨论】:

    • Python 2x 和 3x 之间确实没有必要通用,因为两者一开始就不兼容
    • 我的意思是如果他想替换这 4 个字符以外的东西。我意识到上下文是用于处理 HTML 内容,但只是认为 HTML 转义仅适用于这些字符可能毫无价值,并且对其他人没有帮助
    • 这正是我投票给你的原因:)
    【解决方案4】:
    def escape_html(data):
        return data.replace("&","&amp;").replace('"',"&quot;").replace(">","&gt;").replace("<","&lt;")
    

    【讨论】:

    • 替换顺序很重要。
    【解决方案5】:

    您可以使用xml.sax.saxutils,它提供了escape 方法。 见escaping HTML

    【讨论】:

      猜你喜欢
      • 2011-01-22
      • 2012-08-31
      • 2010-11-08
      • 2012-07-09
      • 1970-01-01
      • 1970-01-01
      • 2012-03-01
      • 1970-01-01
      • 2012-07-05
      相关资源
      最近更新 更多