在 Python 中,URL 解码(也称为百分比解码)可以通过标准库 urllib.parse 模块轻松实现,以下是详细说明和示例:

使用 urllib.parse.unquote()
这是最常用的方法,用于解码 URL 编码的字符串(将 %xx 转换为对应字符)。
示例代码
from urllib.parse import unquote encoded_url = "https://example.com/search?q=hello%20world%21&lang=zh-CN" decoded_url = unquote(encoded_url) print(decoded_url) # 输出: https://example.com/search?q=hello world!&lang=zh-CN
关键点
unquote()会自动处理%20(空格)、%21()等编码字符。- 如果字符串中包含非 ASCII 字符(如中文),
unquote()会直接返回原始字符(无需额外处理)。
处理查询字符串参数
如果需要解码 URL 中的查询参数(如 ?key=value&...),可以使用 parse_qs 或 parse_qsl:
示例代码
from urllib.parse import parse_qs, unquote
url = "https://example.com/search?q=hello%20world%21&lang=zh-CN"
query_string = url.split("?")[1] # 提取查询部分 "q=hello%20world%21&lang=zh-CN"
decoded_params = parse_qs(query_string)
print(decoded_params)
# 输出: {'q': ['hello world!'], 'lang': ['zh-CN']}
说明
parse_qs()返回字典,每个键对应一个值的列表(因为参数可能重复)。- 如果需要扁平化的键值对,使用
parse_qsl():from urllib.parse import parse_qsl print(parse_qsl(query_string)) # 输出: [('q', 'hello world!'), ('lang', 'zh-CN')]
处理特殊字符
某些特殊字符(如 , , )在 URL 中不会被编码,但 unquote() 会保留它们:
encoded = "path/to/file%2Ftest%3Fparam%23hash" decoded = unquote(encoded) print(decoded) # 输出: path/to/file/test?param#hash
其他注意事项
-
编码 vs 解码:
如果需要编码URL,使用urllib.parse.quote():
(图片来源网络,侵删)from urllib.parse import quote original = "hello world!" encoded = quote(original) print(encoded) # 输出: hello%20world%21
-
Python 2 兼容性:
在 Python 2 中,使用from urlparse import unquote(模块名不同)。 -
第三方库:
如果需要更高级的功能(如处理完整的 URL 对象),可以使用requests库:from requests import utils decoded = utils.unquote("hello%20world") print(decoded) # 输出: hello world
| 需求 | 方法 |
|---|---|
| 解码整个 URL | urllib.parse.unquote() |
| 解析查询参数 | urllib.parse.parse_qs() 或 parse_qsl() |
| 编码 URL | urllib.parse.quote() |
| Python 2 兼容 | from urlparse import unquote |
推荐优先使用标准库 urllib.parse,除非有特殊需求(如处理复杂 URL 结构)。

