urllib.parse splits URLs, reads query strings, and applies percent encoding. urlsplit keeps scheme, authority, path, query, and fragment separate, while urlencode produces correctly escaped parameters.
from urllib.parse import parse_qs, urlencode, urlsplit, urlunsplit
parts = urlsplit("https://example.com/search?q=python&page=2")
query = parse_qs(parts.query)
query["page"] = ["3"]
new_url = urlunsplit(parts._replace(query=urlencode(query, doseq=True)))
print(new_url)
How to use it safely
Parsing does not make a URL safe. For redirects or requests, allow only expected schemes, validate the hostname, and account for DNS resolution and internal addresses. When combining a base with external input, remember that urljoin accepts absolute URLs.
To strengthen the foundation, read Python collections guide and type hints guide.
The official Python documentation, accessed July 22, 2026, describes the API, edge cases, and version compatibility.