在python中转义html?

时间:2010-06-22 20:37:53

标签: python html escaping

我有<img src=__string__>字符串可能包含“,我应该怎么做才能逃脱它?

示例:

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

不起作用。

5 个答案:

答案 0 :(得分:12)

在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'

答案 1 :(得分:11)

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

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

答案 2 :(得分:5)

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

答案 3 :(得分:2)

如果您使用的网址(此处为img src)可能包含引号,则应使用网址引用。

对于python,在将URL字符串传递给模板之前使用urllib.quote方法:

img_url = 'test".jpg'
__string__ = urllib.quote(img_url)

答案 4 :(得分:-3)

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

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