HTML 编码器 / 解码器
将特殊字符编码为 HTML 实体,并将其解码回来。
常见问题
代码实现
import html
# Encode: replace <, >, &, ", ' with HTML entities
raw = "<script>alert('XSS')</script> & <b>bold</b>"
encoded = html.escape(raw)
print(encoded)
# <script>alert('XSS')</script> & <b>bold</b>
# Also encode quotes (useful inside HTML attributes)
encoded_all = html.escape(raw, quote=True)
print(encoded_all)
# <script>alert('XSS')</script> & <b>bold</b>
# Decode: convert HTML entities back to plain text
decoded = html.unescape(encoded)
print(decoded)
# <script>alert('XSS')</script> & <b>bold</b>
# Safe injection into a template
user_input = "<img src=x onerror=alert(1)>"
safe_html = f"<p>{html.escape(user_input)}</p>"Comments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.