urllib.parse Splits And Rebuilds Query Strings

urlsplit and parse_qs dissect a URL without touching the network, and urlencode with doseq=True turns list values back into repeated query keys.

PythonData Fetching

Code

pythonsnippet
18 lines
from urllib.parse import parse_qs, urlencode, urlsplit

# 拆解:urlsplit 只做结构切分,不访问网络
parts = urlsplit("https://api.example.com/v2/search?q=red&page=2&tag=a&tag=b#results")
print("scheme  :", parts.scheme)
print("host    :", parts.netloc)
print("path    :", parts.path)
print("query   :", parts.query)
print("fragment:", parts.fragment)

# parse_qs 把查询串还原成字典:同名键的值聚合为列表
params = parse_qs(parts.query)
print("q       :", params["q"])
print("tags    :", params["tag"])

# urlencode 反向生成:doseq=True 让列表值展开成重复键,空格编码成 +
query = urlencode({"q": "red shoes", "page": 2, "tag": ["a", "b"]}, doseq=True)
print("rebuilt :", query)

How it works

From urllib it pulls parse_qs, urlencode, urlsplit — the imports name exactly which library surface the snippet touches.

Top-level bindings parts, params, query hold the demo state — nothing sits inside a function scope.

What to watch for

  • Dependency check: urllib — not built-in, must be present in the project.

Using it

The demo output is labeled (scheme :, host :, path :), so every printed line maps back to its originating operation.

Interactive Tools for This Topic

FAQ

Which packages must be installed first?
Yes. The imports resolve to `urllib`, which the package manager must provide.