← 中文资源

简体中文版本

html.escape 让不可信文本安全渲染

html.escape 把尖括号、& 与引号转成实体,注入的标记保持惰性;quote=False 适配文本节点场景,unescape 在回读时还原原文,属性值同样必须先转义。

阅读英文原文

实现说明

comment、encoded、value 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 预留安装步骤:html 是真实依赖,由包管理器解析。
  • 跑完文件,输出里会留下标记——<input value=。

常见问题

运行之前需要装什么吗?

需要:html 必须在项目里,否则导入在加载时就会失败。

代码示例

import html

# Untrusted text goes into an HTML page: escape it so markup stays inert.
comment = 'Use <b>bold</b> & "quotes" and it\'s 5 < 10'
print(html.escape(comment))

# quote=False leaves quotes alone for text nodes, still escapes angle brackets.
print(html.escape(comment, quote=False))

# unescape reverses the mapping for text pulled back out of HTML.
encoded = "&lt;script&gt;alert(1)&lt;/script&gt;"
print(html.unescape(encoded))

# Escape attribute values too, or a quote character breaks out of the tag.
value = 'name="XSS" onload="alert(1)"'
print(f'<input value="{html.escape(value)}">')