代码之家  ›  专栏  ›  技术社区  ›  Timmy

在python中转义html?

  •  4
  • Timmy  · 技术社区  · 16 年前

    我有一个 <img src=__string__> 但是 一串 可能包含“我该怎么做才能摆脱它?”

    例子:

    __string__ = test".jpg
    <img src="test".jpg">
    

    不起作用。

    5 回复  |  直到 15 年前
        1
  •  11
  •   gomad    16 年前

    如果要转义的值可能包含引号,最好使用 quoteattr 方法: http://docs.python.org/library/xml.sax.utils.html#module-xml.sax.saxutils

    这是在cgi.escape()方法的文档正下方引用的。

        2
  •  11
  •   Maciej Ziarko    15 年前

    在python 3.2中, html 介绍了用于从HTML标记中转义保留字符的模块。

    它有一个功能 html.escape(s, quote=True) . 如果可选标志引号为true,则字符 (") (') 也被翻译。

    用途:

    >>> import html
    >>> html.escape('x > 2 && x < 7')
    'x &gt; 2 &amp;&amp; x &lt; 7'
    
        3
  •  5
  •   ʇsәɹoɈ    16 年前
    import cgi
    s = cgi.escape('test".jpg', True)
    

    http://docs.python.org/library/cgi.html#cgi.escape

    请注意 True 标志指示它转义双引号。如果您还需要转义单引号(如果您是少数使用单引号来包围HTML属性的人之一),请阅读文档链接中关于xml.sax.saxutils.quoteattr()的说明。后者做两种引用,尽管速度大约是后者的三倍:

    >>> timeit.Timer( "escape('asdf\"asef', True)", "from cgi import escape").timeit()
    1.2772219181060791
    >>> timeit.Timer( "quoteattr('asdf\"asef')", "from xml.sax.saxutils import quoteattr").timeit()
    3.9785079956054688
    
        4
  •  2
  •   tcarobruce    16 年前

    如果您使用的URL(作为 img src-here)可能包含引号,您应该使用URL引号。

    对于python,使用 urllib.quote 方法,然后将URL字符串传递到模板:

    img_url = 'test".jpg'
    __string__ = urllib.quote(img_url)
    
        5
  •  -3
  •   eeeeaaii    16 年前

    在Python中转义XML或HTML的最佳方法可能是使用三个引号。请注意,您还可以退出回车。

    """<foo bar="1" baz="2" bat="3">
    <ack/>
    </foo>
    """