HTML Escaping in Python [duplicate]

2019-09-11 17:10发布

问题:

Possible Duplicate:
What's the easiest way to escape HTML in Python?

What's the easiest way to HTML escape characters in Python? I would like to take a list of items and iterate over them, having them changed to HTML escaped characters.

回答1:

Python standard library has cgi module, which provides escape function.

See: http://docs.python.org/library/cgi.html#functions



回答2:

Template engines tend to make your code cleaner and easier to maintain. For example, you can pass the list to the template engine and do the iteration inside the template:

t = Template('{% for item in items %}{{ item }}\n{% endfor %}')
result = t.render(dict(items=some_list))

Most template engines will escape html by default. There are quite a few to choose from, when I'm not not using Django, may favorite is jinja2.

See http://wiki.python.org/moin/Templating for other alternatives.



回答3:

Try something like this (untested, just a sample):

html_convert = {"<": "&lt;", ">": "&gt;", "\"": "&quot;", "&": "&amp;"} #Etc.
html_text = "<div id=\"idk\">Something truly interesting & fun...</div>"
html_list = [char for char in html_text]

for char in html_list:
    if char in html_convert:
        char = html_convert[char]

html_escaped_text = "".join(html_list)