我有一个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的网页抓取工具,它"扫描"网页并从中获取特定内容,然后以该格式返回字符串.

我在C#学到了这一点,但在Python学不到.有人能帮帮我吗?

相关

推荐答案

对于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('&', '&amp;').replace('<', '&l
t;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;'))

为了扭转这种局面,Jake的回答中描述的猎豹功能应该是有效的,但缺少一句话.此版本包括更新的元组,替换顺序颠倒,以避免对称问题:

def html_decode(s):
    """
    Returns the ASCII decoded version of the given HTML string. This does
    NOT remove normal HTML tags like <p>.
    """
    htmlCodes = (
            ("'", '&#39;'),
            ('"', '&quot;'),
            ('>', '&gt;'),
            ('<', '&lt;'),
            ('&', '&amp;')
        )
    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 %}

Django相关问答推荐

Django BooleanField如何使用RadioSelect?

如果密码在Django中未被散列,则对其进行散列

我找不到为什么我的DRF登录测试没有按预期工作

Django mods.py我想要一个函数转到一个变量

社工/社工简戈

如何在Django REST框架中管理序列化程序?

根据当前对象中的多对多字段过滤对象

UpdateView 不会对 from 属性进行数据绑定

为什么 timezone.now 在作为默认值应用于 Django 中的 DateField 时显示future 日期

Django - 将 HTML 输出转换为变量

Django: Admin:在管理员中更改字段的小部件

Django 模板列表的第一个元素

Django 模板:通过扩展模板覆盖包含的子模板块

Django - 无法为具有动态 upload_to 值的 ImageField 创建迁移

使用 Gunicorn 运行 Django - 最佳实践

django-object-permissions Vs django-guardian Vs django-authority

ImportError:升级到 Django 4.0 后无法从 'django.conf.urls' 导入名称 'url'

Django中的自定义排序

获取 django 应用的绝对路径

Django将HttpResponseRedirect返回到带有参数的url