实现说明
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 = "<script>alert(1)</script>"
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)}">')