urllib.parse
Two halves in one module. Parsing: urlsplit / urlparse cut a URL into named parts, urljoin resolves links, urlunsplit rebuilds. Quoting: quote / quote_plus / urlencode percent-encode, unquote / parse_qs decode. Nothing here touches the network — that is urllib.request.
import urllib.parse from urllib.parse import urlsplit, urljoin, urlencode, parse_qs, quote
Demo
from urllib.parse import urlsplit u = urlsplit('https://Shop.Example.com:8443/cart/items?id=7&qty=2#summary') (u.scheme, u.hostname, u.port, u.path, u.query, u.fragment)
urlsplit keeps the host as written in netloc; .hostname lowercases it and drops IPv6 brackets, and .port is an int or None — or a ValueError such as 'Port out of range 0-65535'. Without '//' there is no host at all. On the quoting side, quote keeps '/' unless safe='', and quote_plus writes spaces as + — the form style that parse_qs decodes.
Members
Common patterns
from urllib.parse import urlsplit, parse_qs params = parse_qs(urlsplit(url).query)
from urllib.parse import urlencode url = 'https://example.com/search?' + urlencode({'q': term, 'page': 2})
from urllib.parse import urljoin absolute = urljoin(page_url, href)
from urllib.parse import quote url = 'https://example.com/users/' + quote(username, safe='')
Examples
Pitfalls
from urllib.parse import quote quote('a/b c')
from urllib.parse import quote quote('a/b c', safe='')
from urllib.parse import urljoin urljoin('https://example.com/api/v1', 'users')
from urllib.parse import urljoin urljoin('https://example.com/api/v1/', 'users')
from urllib.parse import parse_qs q = 'R&D' parse_qs(f'dept={q}&page=1')
from urllib.parse import parse_qs, urlencode parse_qs(urlencode({'dept': 'R&D', 'page': 1}))
When to use
- Reading or changing parts of a URL
- Turning relative links into absolute ones
- Encoding values for URLs and decoding query strings
- Fetching URLs → urllib.request, or the requests / httpx packages
- Validating untrusted URLs for security decisions → parse, then check scheme and hostname explicitly
- HTML escaping → html.escape
Notes
FAQ
from urllib.parse import urlsplit; u = urlsplit(url) — then u.scheme, u.hostname, u.port, u.path, u.query and u.fragment. parse_qs(u.query) decodes the query parameters.