Python3的URL解析库urlparse

Python 3 中 urlparse 模块已移至 urllib.parse,需用 from urllib.parse import urlparse 等;核心函数包括 urlparse() 解析 URL、parse_qs()/parse_qsl() 处理查询参数、urlunparse()/urljoin() 构造 URL、quote()/unquote() 编解码。

Python 3 中的 urlparse 模块已重命名并整合进 urllib.parse,不再是独立模块。直接导入 urlparse 会报错(ModuleNotFoundError),正确用法是导入 urllib.parse 下的对应函数。

核心函数:urlparse()

用于将 URL 字符串拆解为结构化对象(ParseResult),包含 scheme、netloc、path、params、query、fragment 六个属性。

  • 示例:from urllib.parse import urlparse
  • result = urlparse("https://user:pass@example.com:8080/path/to/page?name=alice&age=30#section1")
  • 可访问 result.scheme(→ "https")、result.netloc(→ "user:pass@example.com:8080")、result.path(→ "/path/to/page")等

解析查询参数:parse_qs() 和 parse_qsl()

专门处理 URL 中的 query 部分(?key=value&key2=value2)。

  • parse_qs("a=1&b=2&b=3"){'a': ['1'], 'b': ['2', '3']}(值始终为列表,保留重复键)
  • parse_qsl("a=1&b=2&b=3")[('a', '1'), ('b', '2'), ('b', '3')](返回键值对列表,适合遍历或去重)
  • 注意:两者都默认不进行 URL 解码;如需解码,传参 keep_blank_values=True 或配合 unquote()

构造与拼接 URL:urlunparse() 和 urljoin()

反向操作:从部件组装 URL,或基于 base URL 补全相对路径。

  • urlunparse(("https", "example.com", "/api/v1", "", "q=test", "top"))"https://example.com/api/v1?q=test#top"
  • urljoin("https://example.com/base/", "../image.jpg")"https://example.com/image.jpg"
  • urljoin("https://example.com/base/", "/static/css/main.css")"https://example.com/static/css/main.css"(以 / 开头视为绝对路径)

编码与解码:quote()、unquote()、quote_plus()、unquote_plus()

处理 URL 中的非 ASCII 或特殊字符(如空格、中文、符号)。

  • quote("hello world+test")"hello%20world%2Btest"(空格→%20,+ 保持原样)
  • quote_plus("hello world+test")"hello+world%2Btest"(空格→+,更常用于表单提交)
  • unquote("%E4%BD%A0%E5%A5%BD")"你好"unquote_plus("hello+world")"hello world"

基本上就这些。日常使用中,urlparseparse_qsurljoinquote 是最常调用的几个工具,记住模块位置和基本行为就能覆盖绝大多数 URL 处理场景。