【发布时间】:2010-06-22 20:37:53
【问题描述】:
我有一个<img src=__string__>,但字符串可能包含“,我应该怎么做才能逃脱它?
例子:
__string__ = test".jpg
<img src="test".jpg">
没用。
【问题讨论】:
-
这个问题stackoverflow.com/questions/275174/…有一些有用的答案。
我有一个<img src=__string__>,但字符串可能包含“,我应该怎么做才能逃脱它?
例子:
__string__ = test".jpg
<img src="test".jpg">
没用。
【问题讨论】:
在 Python 3.2 中引入了一个新的 html 模块,用于从 HTML 标记中转义保留字符。
它只有一个功能html.escape(s, quote=True)。
如果可选标志引号为真,则字符(") 和(') 也会被翻译。
用法:
>>> import html
>>> html.escape('x > 2 && x < 7')
'x > 2 && x < 7'
【讨论】:
html 不适用于 Python 2,但确实如此。
如果您的转义值可能包含引号,最好使用quoteattr 方法:http://docs.python.org/library/xml.sax.utils.html#module-xml.sax.saxutils
这在 cgi.escape() 方法的文档下方被引用。
【讨论】:
&quot; 的 URL,这不太可能解析为您所定位的资源。
django.utils.html.escape 有效。
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
【讨论】:
如果您使用的 URL(此处为 img src)可能包含引号,则应使用 URL 引用。
对于 python,在将 URL 字符串传递给模板之前使用 urllib.quote 方法:
img_url = 'test".jpg'
__string__ = urllib.quote(img_url)
【讨论】:
在 python 中转义 XML 或 HTML 的最佳方法可能是使用三引号。请注意,您也可以转义回车。
"""<foo bar="1" baz="2" bat="3">
<ack/>
</foo>
"""
【讨论】:
__string__,因为他使用引号 around __string__。