在Python中转义HTML最简单的方法是什么?
cgi.escape似乎是一个可能的select。 它工作正常吗? 有什么更好的吗?
 cgi.escape很好。 它逃脱了: 
-   <至<
-   >到>
-   &to&
这对于所有的HTML都是足够的。
编辑:如果你有非ASCII字符,你也想逃避,包括在另一个编码的文件,使用不同的编码,如克雷格说,只需使用:
 data.encode('ascii', 'xmlcharrefreplace') 
 不要忘记首先使用任何编码的编码将data解码为unicode 。 
 然而,根据我的经验,如果您从开始就一直使用unicode ,那么这种编码就毫无用处。 最后编码在文档头中指定的编码( utf-8为了最大的兼容性)。 
例:
 >>> cgi.escape(u'<a>bá</a>').encode('ascii', 'xmlcharrefreplace') '<a>bá</a> 
 也值得注意(感cgi.escape )是多余的quote参数cgi.escape需要。 将它设置为True , cgi.escape也会转义双引号( " ),以便在XML / HTML属性中使用结果值。 
 编辑:请注意,cgi.escape已被弃用在Python 3.2赞成html.escape ,除了quote默认值为True。 
 在Python 3.2中引入了一个新的html模块,用于从HTML标记中转义保留字符。 
 它有一个函数escape() : 
 >>> import html >>> html.escape('x > 2 && x < 7') 'x > 2 && x < 7' 
  cgi.escape应该是有限的逃避HTML标记和字符实体的转义HTML。 
但是你可能还要考虑编码问题:如果你想要引用的HTML在特定的编码中有非ASCII字符,那么你也必须小心,当你引用时你明智地代表那些。 也许你可以把它们转换成实体。 否则,您应该确保在“源”HTML和其所embedded的页面之间进行了正确的编码转换,以避免损坏非ASCII字符。
如果您想在url中转义HTML,请执行以下操作:
这可能不是OP想要的(这个问题并没有清楚地表明在哪个上下文中使用了转义),但是Python的本地库urllib有一个方法来转义需要被安全包含在URL中的HTML实体。
以下是一个例子:
 #!/usr/bin/python from urllib import quote x = '+<>^&' print quote(x) # prints '%2B%3C%3E%5E%26' 
在这里find文档
还有优秀的markupsafe软件包 。
 >>> from markupsafe import Markup, escape >>> escape("<script>alert(document.cookie);</script>") Markup(u'<script>alert(document.cookie);</script>') 
  markupsafe包是精心devise的,可能是最通用的和Pythonic逃避方法,恕我直言,因为: 
-  返回( Markup)是从unicode派生的类(即isinstance(escape('str'), unicode) == True
- 它正确处理unicodeinput
- 它适用于Python(2.6,2.7,3.3和pypy)
-  它尊重对象的自定义方法(即具有__html__属性的对象)和模板重载(__html_format__)。
  cgi.escape扩展 
 这个版本改进了cgi.escape 。 它也保留空白和换行符。 返回一个unicodestring。 
 def escape_html(text): """escape strings for display in HTML""" return cgi.escape(text, quote=True).\ replace(u'\n', u'<br />').\ replace(u'\t', u' ').\ replace(u' ', u'  ') 
例如
 >>> escape_html('<foo>\nfoo\t"bar"') u'<foo><br />foo "bar"' 
 不是最简单的方法,但仍然简单明了。 与cgi.escape模块的主要区别 – 如果你已经有了& 在你的文字。 正如你从评论中看到的那样: 
cgi.escape版本
 def escape(s, quote=None): '''Replace special characters "&", "<" and ">" to HTML-safe sequences. If the optional flag quote is true, the quotation mark character (") is also translated.''' s = s.replace("&", "&") # Must be done first! s = s.replace("<", "<") s = s.replace(">", ">") if quote: s = s.replace('"', """) return s 
正则expression式版本
 QUOTE_PATTERN = r"""([&<>"'])(?!(amp|lt|gt|quot|#39);)""" def escape(word): """ Replaces special characters <>&"' to HTML-safe sequences. With attention to already escaped characters. """ replace_with = { '<': '>', '>': '<', '&': '&', '"': '"', # should be escaped in attributes "'": ''' # should be escaped in attributes } quote_pattern = re.compile(QUOTE_PATTERN) return re.sub(quote_pattern, lambda x: replace_with[x.group(0)], word) 
通过BeautifulSoup4 :
 >>> bs4.dammit import EntitySubstitution >>> esub = EntitySubstitution() >>> esub.substitute_html("r&d") 'r&d'