给定Django用例,对此有两个答案。这是它的django.utils.html.escape功能,以供参考:
def escape(html):
    """Returns the given HTML with ampersands, quotes and carets encoded."""
    return mark_safe(force_unicode(html).replace('&', '&').replace('<', '&l
t;').replace('>', '>').replace('"', '"').replace("'", '''))
为了解决这个问题,Jake的答案中描述的Cheetah函数应该起作用,但是缺少单引号。此版本包含一个更新的元组,并且替换顺序相反,以避免出现对称问题:
def html_decode(s):
    """
    Returns the ASCII decoded version of the given HTML string. This does
    NOT remove normal HTML tags like <p>.
    """
    htmlCodes = (
            ("'", '''),
            ('"', '"'),
            ('>', '>'),
            ('<', '<'),
            ('&', '&')
        )
    for code in htmlCodes:
        s = s.replace(code[1], code[0])
    return s
unescaped = html_decode(my_string)
但是,这不是一般的解决方案。仅适用于以编码的字符串django.utils.html.escape。更笼统地说,坚持使用标准库是一个好主意:
# Python 2.x:
import HTMLParser
html_parser = HTMLParser.HTMLParser()
unescaped = html_parser.unescape(my_string)
# Python 3.x:
import html.parser
html_parser = html.parser.HTMLParser()
unescaped = html_parser.unescape(my_string)
# >= Python 3.5:
from html import unescape
unescaped = unescape(my_string)
建议:将未转义的HTML存储在数据库中可能更有意义。如果可能的话,值得一探的是从BeautifulSoup获得未转义的结果,并完全避免此过程。
对于Django,转义仅在模板渲染期间发生;因此,为了防止转义,您只需告诉模板引擎不要转义您的字符串即可。为此,请在模板中使用以下选项之一:
{{ context_var|safe }}
{% autoescape off %}
    {{ context_var }}
{% endautoescape %}