我有一个HTML编码的字符串:
'''<img class="size-medium wp-image-113"\
style="margin-left: 15px;" title="su1"\
src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg"\
alt="" width="300" height="194" />'''
我想将其更改为:
<img class="size-medium wp-image-113" style="margin-left: 15px;"
title="su1" src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg"
alt="" width="300" height="194" />
我希望将其注册为HTML,以便浏览器将其呈现为图像,而不是显示为文本。
字符串是这样存储的,因为我使用的是一个名为BeautifulSoup
的web抓取工具,它“扫描”网页并从中获取特定内容,然后以该格式返回字符串。
我已经在C#中找到了如何做到这一点,但在Python中却没有。有人能帮帮我吗?
相关
发布于 2008-11-08 21:40:38
对于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("'", '''))
要扭转这种情况,杰克的答案中描述的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 %}
发布于 2011-08-17 13:51:23
使用标准库:
尝试:从html导入转义# print(escape("<"))
尝试:从html导入print(unescape(">"))除外# python 3.4+除ImportError: try:从html.parser导入HTMLParser # python 3.x (<3.4)除外ImportError:从HTMLParser导入HTMLParser # python 2.x unescape = HTMLParser().unescape python
发布于 2009-01-16 01:12:54
对于html编码,有来自标准库的cgi.escape:
>> help(cgi.escape)
cgi.escape = 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.
对于html解码,我使用以下代码:
import re
from htmlentitydefs import name2codepoint
# for some reason, python 2.5.2 doesn't have this one (apostrophe)
name2codepoint['#39'] = 39
def unescape(s):
"unescape HTML code refs; c.f. http://wiki.python.org/moin/EscapingHtml"
return re.sub('&(%s);' % '|'.join(name2codepoint),
lambda m: unichr(name2codepoint[m.group(1)]), s)
对于更复杂的情况,我使用BeautifulSoup。
https://stackoverflow.com/questions/275174
复制相似问题