urllib.parse.ParseResultBytes
Give urlparse, urlsplit or urldefrag bytes and every field comes back as bytes, in a *Bytes result class. Internally the bytes are decoded as ASCII, parsed as str and encoded again — so the input must be pure ASCII, and str and bytes arguments cannot be mixed.
Demo
from urllib.parse import urlsplit urlsplit('https://Example.com:8080/a?q=1#f'.encode())
Bytes input is decoded with the ascii codec before parsing, so 'café' encoded as UTF-8 fails at the first byte of é: "'ascii' codec can't decode byte 0xc3 in position ...". Everything else works as for str: .hostname is lowercased bytes, .port is an int, geturl() returns bytes and .decode() converts the whole result to ParseResult.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| scheme, netloc, path, params, query, fragment | bytes | yes | ParseResultBytes fields (SplitResultBytes has no params; DefragResultBytes has url and fragment). Usually created by the parse functions, not by hand. |
Return value
ParseResultBytes | SplitResultBytes | DefragResultBytes — Named tuples of bytes fields. .decode(encoding="ascii", errors="strict") returns the str class; geturl() returns bytes.
Common patterns
from urllib.parse import urlsplit parts = urlsplit(raw_url_bytes) host = parts.hostname.decode('ascii')
from urllib.parse import urlparse b = urlparse(url).encode('utf-8') s = b.decode('utf-8')
Examples
Pitfalls
from urllib.parse import urlsplit urlsplit('https://example.com/café'.encode())
from urllib.parse import urlsplit, quote urlsplit(quote('https://example.com/café', safe=':/').encode()).path
from urllib.parse import urlsplit urlsplit(b'example.com/a', 'http')
from urllib.parse import urlsplit urlsplit(b'example.com/a', b'http').scheme
from urllib.parse import urlparse urlparse('https://example.com/café').encode()
from urllib.parse import urlparse urlparse('https://example.com/café').encode('utf-8').path
When to use
- URLs that arrive as bytes (sockets, binary logs) and are pure ASCII
- Keeping a bytes pipeline bytes end to end
- Text URLs → the str functions and ParseResult / SplitResult
- Non-ASCII bytes → percent-encode them, or decode to str first
Notes
FAQ
Yes, since Python 3.2: urlparse(b'https://example.com/') returns a ParseResultBytes with bytes fields. The bytes must be ASCII — non-ASCII bytes raise UnicodeDecodeError.