如果您正在使用Web框架和像Jinja2这样的模板引擎,那么模板引擎或框架可能就是为此而构建的.
cgi模块中有一些东西可以帮助你:
cgi.escape('malicious code here'),请参阅:http://docs.python.org/library/cgi.html#cgi.escape
Jinja2还提供了转义:
from jinja2 import utils
str(utils.escape('malicious code here'))
Run Code Online (Sandbox Code Playgroud)
Strip -o-Gram库看起来相当不错。我还没有正确检查过它,但看起来它做得很好(即可以将您指定的 HTML 标签列入白名单,以及转义任何令人讨厌的 HTML 标签)。
这是从该页面引用的示例用法片段:
from stripogram import html2text, html2safehtml
mylumpofdodgyhtml # a lump of dodgy html ;-)
# Only allow <b>, <a>, <i>, <br>, and <p> tags
mylumpofcoolcleancollectedhtml = html2safehtml(mylumpofdodgyhtml,valid_tags=("b", "a", "i", "br", "p"))
# Don't process <img> tags, just strip them out. Use an indent of 4 spaces
# and a page that's 80 characters wide.
mylumpoftext = html2text(mylumpofcoolcleancollectedhtml,ignore_tags=("img",),indent_width=4,page_width=80)
Run Code Online (Sandbox Code Playgroud)
希望有帮助。