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.
Code
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
Query String ParserParse a query string or URL into decoded key-value rows, preserving repeated keys and empty values for debugging and API work.URL Query String SerializerParse a URL query string into decoded key/value pairs or serialize key=value lines into a percent-encoded query string with duplicate-key detection.Base64url CodecEncode and decode Base64url, the URL- and filename-safe variant that swaps + and / for - and _ and omits padding.GraphQL Query FormatterPretty-print a GraphQL query by indenting selection sets by brace depth and normalizing punctuation spacing.
FAQ
- Which packages must be installed first?
- Yes. The imports resolve to `urllib`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.