Python html 库用法详解

html 是 Python 的标准库之一,主要用于处理 HTML 相关的编码和解码操作。它提供了两个核心函数:escape()unescape()

基本功能

1、html.escape() - HTML 编码

将特殊字符转换为 HTML 实体,防止 XSS 攻击或确保 HTML 正确显示

python 复制代码
import html

text = '<script>alert("XSS")</script>'
escaped = html.escape(text)
print(escaped)
# 输出: &lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt;

默认转义的字符:

  • <&lt;

  • >&gt;

  • &&amp;

  • "&quot;

可选参数:

python 复制代码
html.escape(text, quote=False)  # 不转义引号(")

2、html.unescape() - HTML 解码

将 HTML 实体转换回普通字符。

python 复制代码
import html

escaped_text = "&lt;div&gt;Hello &amp; Welcome&lt;/div&gt;"
clean_text = html.unescape(escaped_text)
print(clean_text)
# 输出: <div>Hello & Welcome</div>
相关推荐
老姚---老姚4 分钟前
在windows下编译go语言编写的dll库
开发语言·windows·golang
diediedei15 分钟前
模板编译期类型检查
开发语言·c++·算法
Stream_Silver19 分钟前
【Agent学习笔记3:使用Python开发简单MCP服务】
笔记·python
穿过锁扣的风24 分钟前
零基础入门 Python 爬虫:从基础到实战,爬取虎扑 / 豆瓣 / 图片全掌握
开发语言·爬虫·python
Stream_Silver28 分钟前
【Agent学习笔记2:深入理解Function Calling技术:从原理到实践】
笔记·python
love530love1 小时前
技术复盘:llama-cpp-python CUDA 编译实战 (Windows)
人工智能·windows·python·llama·aitechlab·cpp-python·cuda版本
一切尽在,你来1 小时前
C++多线程教程-1.2.1 C++11/14/17 并发特性迭代
开发语言·c++
80530单词突击赢1 小时前
C++入门指南:从零到精通
开发语言·c++
小突突突1 小时前
浅谈Java中的反射
java·开发语言
csbysj20201 小时前
JSP 发送邮件教程
开发语言