On this page
urllib
Prev: unittest | Up: stdlib_module | Next: uuid
Rel: email, json, mailbox, mimetypes, base64
Ref: docs.python.org — urllib
Tags: #public #python3 #stdlib
Import
from urllib import parse, request, error
Overview
Package grouping Python's standard-library URL and HTTP utilities across four submodules: urllib.parse (URL parsing, joining, quoting, and query encoding), urllib.request (HTTP/HTTPS client), urllib.error (HTTPError, URLError), and urllib.robotparser. Always import the specific submodule (from urllib.parse import ..., from urllib.request import ...) rather than bare import urllib.
Quick Start
from urllib.parse import parse_qs, urlencode, urljoin, urlsplit
base = "https://example.org/v1/"
endpoint = urljoin(base, "search") + "?" + urlencode({"q": "python stdlib", "page": 2})
parts = urlsplit(endpoint)
assert parts.scheme == "https"
assert parts.netloc == "example.org"
assert parse_qs(parts.query) == {"q": ["python stdlib"], "page": ["2"]}
Implementation Walkthrough
1. Building Safe Requests with Explicit Timeouts & Error Handling
When using urllib.request, construct a Request with explicit headers, set a timeout, and cap bytes read from the stream:
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
def read_limited(url: str, *, timeout: float = 10.0, max_bytes: int = 1_000_000) -> bytes:
req = Request(url, headers={"Accept": "application/json"})
try:
with urlopen(req, timeout=timeout) as resp:
data = resp.read(max_bytes + 1)
if len(data) > max_bytes:
raise ValueError("Response exceeded max_bytes")
return data
except HTTPError as exc:
raise RuntimeError(f"HTTP {exc.code}: {exc.reason}") from exc
except URLError as exc:
raise ConnectionError(f"Request failed: {exc.reason}") from exc
2. Percent-Encoding Path Segments & Query Strings
from urllib.parse import quote, unquote
encoded = quote("notes/my file #1.md", safe="/")
assert encoded == "notes/my%20file%20%231.md"
assert unquote(encoded) == "notes/my file #1.md"
Gotchas & Boundaries
- Bare
import urllibdoes not exposeurllib.requestorurllib.parse: Import the submodule you need explicitly. - Always pass
timeout=: Without it, a stalled connection can block indefinitely. - Validate URL schemes before opening: Restrict untrusted URLs to
httpandhttps. - No built-in connection pooling: For persistent HTTP/1.1 connections, use
http.client.HTTPSConnection(in http) or a pooled client.
Linked from
- tuts/python3
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/nturl2path
- tuts/python3/stdlib_module/socket
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/unittest
- tuts/python3/stdlib_module/uuid
- tuts/python3/tutorials/popular_application_domains
- tuts/python3/tutorials/popular_application_domains/automation_devops_and_web_scraping
- tuts/python3/tutorials/popular_application_domains/web_development_and_apis
Related notes
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/unittest Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/uuid Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/base64 Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/email Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/http Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/json Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/mailbox Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/mimetypes Linked here; shared tags: #stdlib