How to take a website screenshot in Python
By URLBooth · Published · Last updated
To take a website screenshot in Python, send one authenticated POST request to the URLBooth endpoint /v1/screenshots with a JSON body such as {"url": "https://example.com"} and an Authorization: Bearer key. The response body is the image itself, so you write response.content to a file.
What is the minimal Python example with requests?
Install requests with pip install requests, export your key as URLBOOTH_API_KEY and run this. The API needs the Pro plan; you create the key in the dashboard under API keys. The capture happens inside the request, so there is nothing to poll.
import osimport requestsresponse = requests.post("https://urlbooth.com/v1/screenshots",headers={"Authorization": f"Bearer {os.environ['URLBOOTH_API_KEY']}"},json={"url": "https://example.com"},timeout=60,)if not response.ok:error = response.json()["error"]raise RuntimeError(f"{error['code']}: {error['message']} ({error['requestId']})")with open("screenshot.png", "wb") as file:file.write(response.content)print("saved", response.headers["X-Screenshot-Id"])
Two details matter. Pass the body with json=, which sets the Content-Type header for you. And always set timeout: requests has no default timeout, so a stalled connection would hang your script forever. Captures usually take a few seconds and the server gives up after about 45, so 60 seconds leaves room without hiding real failures.
Can you do it with only the standard library?
Yes. If you cannot add dependencies, urllib.request does the same job. Two differences from requests: you encode the JSON yourself and set the content type by hand, and any non-2xx status raises urllib.error.HTTPError. That exception object is also a readable response, so json.load(exc) gives you the error payload.
import jsonimport osimport urllib.errorimport urllib.requestrequest = urllib.request.Request("https://urlbooth.com/v1/screenshots",data=json.dumps({"url": "https://example.com", "format": "webp"}).encode(),headers={"Authorization": f"Bearer {os.environ['URLBOOTH_API_KEY']}","Content-Type": "application/json",},method="POST",)try:with urllib.request.urlopen(request, timeout=60) as response:screenshot_id = response.headers["X-Screenshot-Id"]with open("screenshot.webp", "wb") as file:file.write(response.read())except urllib.error.HTTPError as exc:error = json.load(exc)["error"]raise RuntimeError(f"{error['code']}: {error['message']}") from excprint("saved", screenshot_id)
How do you change the device, format or full-page capture?
Add fields to the JSON dict. The fields are url, device, format (png, jpeg or webp), fullPage, cleanup and frame. Remember that Python spells booleans True and False; the json= argument converts them to JSON true and false. Unknown fields are rejected with a 400, so a typo fails loudly. Device ids such as macbook-pro-14, iphone-17-pro and ipad-air-11 are listed in the API docs.
import osimport requestsresponse = requests.post("https://urlbooth.com/v1/screenshots",headers={"Authorization": f"Bearer {os.environ['URLBOOTH_API_KEY']}"},json={"url": "https://example.com","device": "macbook-pro-14","format": "jpeg","frame": True,"cleanup": True,},timeout=60,)response.raise_for_status()with open("pricing.jpg", "wb") as file:file.write(response.content)
raise_for_status() is fine for a quick script, but it throws away the JSON error body. Use the explicit check from the first example when you want the error code and request id.
Should you stream the response to a file?
For most captures, no: holding response.content in memory is simpler. Full-page captures of long pages are larger (images over 10 MB are rejected), and when a worker processes many of them in parallel it is reasonable to stream. Pass stream=True and copy chunks with iter_content. Use the context manager so the connection is released even if the write fails, and note the tuple timeout: the first value is the connect timeout, the second is the read timeout between bytes.
import osimport requestswith requests.post("https://urlbooth.com/v1/screenshots",headers={"Authorization": f"Bearer {os.environ['URLBOOTH_API_KEY']}"},json={"url": "https://example.com", "fullPage": True},timeout=(5, 60),stream=True,) as response:if not response.ok:error = response.json()["error"]raise RuntimeError(f"{error['code']}: {error['message']}")with open("full-page.png", "wb") as file:for chunk in response.iter_content(chunk_size=64 * 1024):file.write(chunk)
How do you get a saved screenshot later?
Every successful response carries an X-Screenshot-Id header and an X-Expires-At header. URLBooth keeps the capture for two days, and you can fetch it again with a GET using the same key. Store the id if a later job needs the image, or if your process crashed before it finished writing the file.
import osimport requestsscreenshot_id = "paste-the-X-Screenshot-Id-value"response = requests.get(f"https://urlbooth.com/v1/screenshots/{screenshot_id}/image",headers={"Authorization": f"Bearer {os.environ['URLBOOTH_API_KEY']}"},timeout=60,)response.raise_for_status()with open("again.png", "wb") as file:file.write(response.content)
How do you handle errors and rate limits in Python?
Errors come back as JSON: {"error": {"code", "message", "requestId"}}. Check response.ok before touching the body as an image. Pro allows 60 requests per minute, 10 concurrent captures and 10,000 screenshots per day. When you exceed the per-minute or concurrency limit you get 429 rate_limited with a Retry-After header; daily_limit_reached is also a 429 but resets at 00:00 UTC, so do not loop on it. Retry 503 capture_unavailable and 504 capture_timeout with backoff. Do not retry 400 invalid_request, 401 unauthorized or 402 subscription_required, and treat 502 capture_failed as a problem with the target site.
import osimport timeimport requestsRETRYABLE = {429, 503, 504}def capture(body, attempts=3):for attempt in range(1, attempts + 1):response = requests.post("https://urlbooth.com/v1/screenshots",headers={"Authorization": f"Bearer {os.environ['URLBOOTH_API_KEY']}"},json=body,timeout=60,)if response.ok:return response.contenterror = response.json()["error"]if response.status_code not in RETRYABLE or attempt == attempts:raise RuntimeError(f"{error['code']} (request {error['requestId']})")wait = int(response.headers.get("Retry-After", 2**attempt))time.sleep(wait)image = capture({"url": "https://example.com"})
How do you capture many URLs concurrently?
A plain loop with requests is serial: one capture at a time, a few seconds each. To go faster, use httpx (pip install httpx) with asyncio and cap in-flight requests with a semaphore. Ten is the account limit, so a semaphore of 10 keeps you under it. The per-minute limit of 60 still applies, so a big batch should also pace itself or lean on the retry helper. A ThreadPoolExecutor with max_workers=10 works equally well if you prefer threads.
import asyncioimport osimport httpxURLS = ["https://example.com", "https://example.org", "https://example.net"]async def capture(client, semaphore, index, url):async with semaphore:response = await client.post("/v1/screenshots", json={"url": url})response.raise_for_status()with open(f"shot-{index}.png", "wb") as file:file.write(response.content)async def main():semaphore = asyncio.Semaphore(10)async with httpx.AsyncClient(base_url="https://urlbooth.com",headers={"Authorization": f"Bearer {os.environ['URLBOOTH_API_KEY']}"},timeout=60,) as client:await asyncio.gather(*(capture(client, semaphore, i, url) for i, url in enumerate(URLS)))asyncio.run(main())
When should you run a headless browser yourself instead?
If you already operate Playwright for tests, need to log in or click through a flow before capturing, or capture only internal pages, run the browser yourself. The API only captures public http and https URLs. If you want screenshots without maintaining browser binaries, fonts and memory limits in your Python deployment, the API is less work. The trade-offs are covered in screenshot API vs running Puppeteer yourself.
Where to go next
- API reference for every option, device and error code.
- Pricing: Pro is $20 per month.
- How to take a website screenshot with an API for the language-neutral overview.
- For other languages, see the Node.js screenshot guide, PHP screenshot guide and Go screenshot guide.