

Everything you need to call the Scraping Penguins Scraper API: how to authenticate, every field you can send to POST /api/extract, what comes back, what each error means and what a request costs.
The API has one endpoint, POST /api/extract. You send a JSON body with the URL you want and the outputs you need, and you get back a JSON document with those outputs.
Three flags choose the outputs. At least one must be true, and you can combine them in one request:
httpResponseBody: the body of the page fetched with a plain HTTP request, as the site sent it. Fast and the cheapest option. Use it for HTML pages, JSON APIs, files, and anything that doesn't need JavaScript to show its content.browserHtml: the HTML of the page after a browser has loaded it and run its JavaScript, and after any actions you ask for. Use it for single-page apps and pages that build their content in the browser.screenshot: an image of the page as the browser shows it.Bodies, HTML and images come back base64-encoded, so the response is always valid JSON. Decode them before use (see Decoding the response).
Get your API URL and API key from your dashboard. Sign in to your Scraping Penguins dashboard. Your API URL is the Endpoint in the Quick start card on the Home page, and your key is on the API key page. Copy both. Your API URL may be unique to your account, so always use the one shown in your dashboard. On this page it appears as https://YOUR_API_URL, and your key as YOUR_API_KEY.
The full key is shown only once, when it is created. If you lose it, generate a new one on the API key page. A new key can take up to about 2 minutes to start working; until then, requests with it get 401.
Check your credits. Requests are paid with credits, and your balance is on the Home page. With 0 credits, requests get 402.
Send your first request. This one fetches a page over HTTP:
curl -X POST https://YOUR_API_URL/api/extract \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com", "httpResponseBody": true}'Read the result. statusCode is the status the site answered with, and httpResponseBody holds the page, base64-encoded. Decode it to get the HTML. The code examples show how in Python and Node.js.
Every request to /api/extract needs your API key. Send it in one of these two ways:
x-api-key header (recommended): x-api-key: YOUR_API_KEY.curl -u YOUR_API_KEY:, or the header Authorization: Basic followed by the standard base64 of YOUR_API_KEY:.# x-api-key header
curl -X POST https://YOUR_API_URL/api/extract \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com", "httpResponseBody": true}'
# HTTP Basic, key as the username
curl -X POST https://YOUR_API_URL/api/extract \
-u "YOUR_API_KEY:" \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com", "httpResponseBody": true}'If you send more than one, the request is accepted when any of them holds a valid key.
A missing, unknown or revoked key gets 401. A suspended account, or one with 0 credits, gets 402. Keep your key secret: anyone who has it can spend your credits. If it leaks, generate a new one on the API key page and update your code.
Send a JSON object with the header Content-Type: application/json. The body must be uncompressed (no Content-Encoding) and at most 2 MiB. Field names are case-sensitive. Leave out the fields you don't need.
Browser options apply whenever the page is loaded in a browser, that is, when browserHtml or screenshot is true. HTTP options apply to the httpResponseBody fetch. When you combine httpResponseBody with browserHtml or screenshot, the page is fetched both ways in the same request and you get all the outputs.
| Field | Type | Default | Description |
|---|---|---|---|
| Outputs (choose at least one) | |||
url | string | required | Required. The page to fetch: an absolute http:// or https:// URL with a host, such as https://example.com/page. Addresses on private or local networks, such as localhost, are rejected with 400. |
httpResponseBody | boolean | false | Fetch the URL with a plain HTTP request. Returns the body in httpResponseBody and the response headers in httpResponseHeaders. |
browserHtml | boolean | false | Load the URL in a browser, let its JavaScript run, perform your actions, and return the resulting HTML in browserHtml. |
screenshot | boolean | false | Return an image of the page in screenshot. The page is loaded in a browser even when browserHtml is false; the HTML is then not returned. |
| HTTP options | |||
customHttpRequestHeaders | array | β | Headers to send to the site, as a list of {"name": "β¦", "value": "β¦"} objects, for example referer, accept-language or cookie. Used by the HTTP fetch and by the browser, for the page and everything it loads. |
httpRequestMethod | string | "GET" | HTTP method for the httpResponseBody fetch: GET, POST, PUT, PATCH, DELETE or OPTIONS, in uppercase. The browser always loads the page with GET. |
httpRequestText | string | β | Body to send with the httpResponseBody fetch, as text, for example a JSON or form-encoded string. Use it with POST, PUT or PATCH, and set a matching content-type in customHttpRequestHeaders. |
httpResponseBodyOnError | boolean | false | When the site answers the httpResponseBody fetch with a non-2xx status, return its body, headers and finalUrl as for a 2xx answer, with the site's code in statusCode. Use it to read error pages. Without it, a non-2xx answer returns only statusCode. In a combined request, a non-2xx HTTP answer means the browser outputs are not returned. Non-2xx answers are never charged. |
| Browser options | |||
actions | array | β | Steps to perform on the page after it loads, in order: wait for elements, click, type. See Actions. |
responseCookies | boolean | false | Return the cookies the page set, in responseCookies. |
| Screenshot options | |||
screenshotFullPage | boolean | false | Capture the whole height of the page instead of the visible 1920Γ1080 area. Very tall pages are cut off; see screenshotTruncated. |
screenshotQuality | integer | 60 | Image quality of screenshot, from 1 to 100. Higher means sharper and larger. Values outside the range are brought into it. |
screenshotDeviceScaleFactor | integer | 1 | Pixel density. 1 is standard; 2 gives a sharper, high-density image with four times as many pixels (and a larger file). Values are kept within the range the service allows. |
screenshotBrowserFrame | boolean | false | Also return, in screenshotBrowserFrame, a copy of the screenshot inside a browser-window frame whose address bar shows the final URL. Handy for previews and as proof that a page was visited. The plain screenshot is still returned. |
screenshotFramedFormat | string | "webpNearLossless" | Format of screenshotBrowserFrame: webpNearLossless (smaller and visually identical) or png (lossless). |
| Image extraction | |||
imageSelector | string | β | Return the page's images. A CSS selector for the image elements you want, such as img for all of them or .gallery img. Each matching element gives one image: the version the page actually displayed. Requires browserHtml: true; without it the request gets 400. Leave it out, or send an empty string, to skip images. |
maxImageCount | integer | β | Maximum number of images returned with their data. Images past it are listed with status: "omitted_cap" and no data. Defaults to the service limit and can't go above it. |
maxImageBytes | integer | β | Maximum size, in bytes, of a single image returned with its data. Larger images are listed with status: "omitted_too_large". Defaults to the service limit and can't go above it. |
maxTotalImageBytes | integer | β | Maximum total size, in bytes, of the image data in one response. Images that would go past it are listed with status: "omitted_cap". Defaults to the service limit and can't go above it. |
{
"url": "https://example.com/products?page=2",
"httpResponseBody": true,
"browserHtml": true,
"httpRequestMethod": "GET",
"customHttpRequestHeaders": [
{ "name": "accept-language", "value": "en-US,en;q=0.9" },
{ "name": "referer", "value": "https://example.com/" }
],
"responseCookies": true,
"actions": [
{ "action": "waitForSelector", "selector": { "type": "css", "value": "#products" } }
]
}actions lets you interact with the page before its HTML, screenshot, cookies and images are captured. Actions run whenever the page is loaded in a browser (browserHtml or screenshot).
Actions run one after another, in the order you list them, with no pause in between. If one action's effect must be visible before the next one runs (for example, a click that loads new content), put a waitForSelector or waitForNetworkIdle between them. type focuses its field itself, so you don't need a click before it.
If an action can't be completed (the element never appears, isn't ready, or a wait runs out of time), the request stops and returns HTTP 200 with statusCode: 417 and the reason in message. These requests are not charged.
| Action | What it does | Fields it uses |
|---|---|---|
waitForSelector | Waits until an element matching selector reaches state. | selector, state, timeoutMs |
click | Clicks the element matching selector. | selector, timeoutMs, actionabilityTimeoutMs, effectObservationMs, maxRetries |
type | Focuses the field matching selector and types each string in values, in order. | selector, values, timeoutMs, actionabilityTimeoutMs |
waitForResponse | Waits until the page receives a response whose URL matches urlPattern and whose status is in statusFilter. | urlPattern, statusFilter, timeoutMs |
waitForNetworkIdle | Waits until the page has had no requests in progress for idleMs milliseconds. | idleMs, timeoutMs |
| Field | Type | Default | Description |
|---|---|---|---|
action | string | required | Required. One of the five action types above. |
selector | object | β | The element to act on: {"type": "css", "value": "#submit"}. value is a CSS selector and type is css. Required for waitForSelector, click and type. |
values | array of strings | β | type only. The text to type, one string after another. |
state | string | "attached" | waitForSelector only. attached: the element is in the page. visible: it is also displayed, not hidden or transparent, and has a size. hidden: it is not visible. detached: it has been removed from the page. |
urlPattern | string | β | waitForResponse only, required. A regular expression matched against the full URL of each response. |
statusFilter | array of integers | 2xx | waitForResponse only. The status codes that count, such as [200, 304]. Leave it out to accept any 2xx. |
idleMs | integer | 500 | waitForNetworkIdle only. How long, in milliseconds, the page must go without requests in progress. |
timeoutMs | integer | 30000 | How long to wait, in milliseconds, before the action fails. For click and type without the options below, it counts in whole seconds (rounded down), so use at least 1000. |
actionabilityTimeoutMs | integer | 3000 | click and type. When set, the action first waits up to this long for the element to be ready: in the page, visible, not moving, not covered by another element, and enabled. Without it, the action runs as soon as the element is in the page, even if it is hidden. |
effectObservationMs | integer | 200 | click only. When set, after each click the API watches this long for an effect: a new request, a navigation or a change in the page. If nothing happens, it clicks again. |
maxRetries | integer | 3 | click only. How many more times to click when a click has no effect. Setting any of actionabilityTimeoutMs, effectObservationMs or maxRetries turns on these readiness and effect checks for a click; the defaults shown apply once they are on. |
"actions": [
{ "action": "waitForSelector", "selector": { "type": "css", "value": "#cookie-banner" }, "state": "visible", "timeoutMs": 10000 },
{ "action": "click", "selector": { "type": "css", "value": "#cookie-banner .accept" }, "actionabilityTimeoutMs": 3000 },
{ "action": "type", "selector": { "type": "css", "value": "input[name=q]" }, "values": ["wireless headphones"] },
{ "action": "click", "selector": { "type": "css", "value": "button[type=submit]" } },
{ "action": "waitForResponse", "urlPattern": "/api/search", "statusFilter": [200] },
{ "action": "waitForNetworkIdle", "idleMs": 1000 }
]When the API could process your request, it answers HTTP 200 with a JSON object. Always check statusCode in the body: it is the site's status, and it can be an error even though the HTTP status is 200 (see Errors).
{
"request": { "url": "https://example.com", "httpResponseBody": true, "browserHtml": false, β¦ },
"statusCode": 200,
"httpResponseBody": "PCFkb2N0eXBlIGh0bWw+PGh0bWw+Li4uPC9odG1sPg==",
"httpResponseHeaders": [
{ "name": "content-type", "value": "text/html; charset=UTF-8" }
],
"finalUrl": "https://example.com/",
"capturedAt": "2026-11-24T15:04:05.123456789Z"
}| Field | Type | Description |
|---|---|---|
request | object | Your request, echoed back with the defaults filled in. |
statusCode | integer | The site's status. For the httpResponseBody fetch, the status the site answered with. When the page was loaded in a browser (browserHtml or screenshot), a successful load currently reports 201; a load the site answered with 400 or more comes back as an error with that status. When you ask for both, the browser's value is returned. |
httpResponseBody | string (base64) | Present when you set httpResponseBody. The response body, base64-encoded. It can be HTML, JSON, an image, a PDF or anything else; check the content-type in httpResponseHeaders. |
browserHtml | string (base64) | Present when you set browserHtml. The page's HTML after it loaded and your actions ran, base64-encoded UTF-8. |
httpResponseHeaders | array | The site's response headers, as {"name": "β¦", "value": "β¦"} objects. Filled for the httpResponseBody fetch; an empty list when only the browser was used. |
responseCookies | array | Present when you set responseCookies and the page set cookies. See Cookie fields. |
screenshot | string (base64) | Present when you set screenshot. A WebP image, base64-encoded. A capture taller or wider than 16,383 pixels comes back as PNG instead; tell them apart by the first bytes (WebP starts with RIFF, PNG with \x89PNG). A screenshot bigger than the service's size limit is left out of the response. |
screenshotBrowserFrame | string (base64) | Present when you set screenshot and screenshotBrowserFrame. The screenshot inside a browser-window frame, base64-encoded, in the format chosen with screenshotFramedFormat. |
screenshotTruncated | boolean | Present for full-page screenshots. true when the page was bigger than the capture limit (20,000 pixels high or 30 million pixels in all) and its bottom was cut off; false when the whole page fit. |
images | array | Present when you sent imageSelector. One entry per distinct image; identical images appear once. See Image fields. |
finalUrl | string | The URL after redirects. When the page was loaded in a browser, it also reflects redirects the page made itself. |
capturedAt | string | When the capture finished: UTC, ISO 8601 with nanoseconds, for example 2026-11-24T15:04:05.123456789Z. |
Each entry in images has these fields. Image bytes are returned exactly as the site served them, without conversion. mimeType, sizeBytes, width, height and sha256 are missing when the image's bytes weren't available (blocked_ssrf and fetch_failed).
| Field | Type | Description |
|---|---|---|
url | string | The image URL from the matching element: the version the page actually displayed. |
finalUrl | string | The URL the image was finally served from, after redirects. |
mimeType | string | The image's content type, such as image/jpeg. |
sizeBytes | integer | Size of the original image, in bytes (before base64). |
width | integer | Width of the image, in pixels. |
height | integer | Height of the image, in pixels. |
sha256 | string | Lowercase hex SHA-256 of the original bytes. Identical images share it and appear only once. |
status | string | Whether data is included, and why not when it isn't. See the values below. |
data | string (base64) | The original image bytes, base64-encoded. Present only when status is included. |
statusincluded | The bytes are in data. |
omitted_too_large | The image is larger than maxImageBytes. |
omitted_cap | The image is past maxImageCount, or it would take the response past maxTotalImageBytes. |
blocked_ssrf | The image's address is on a private or local network, so it was not returned. |
fetch_failed | The page never loaded the image (for example, a lazy-loaded image that was never shown) or its download failed. |
| Field | Type | Description |
|---|---|---|
name | string | Cookie name. |
value | string | Cookie value. |
domain | string | Domain the cookie applies to, such as .example.com. |
path | string | Path the cookie applies to. |
expires | number | Expiry as a Unix timestamp in seconds. -1 for a session cookie. |
size | integer | Size of the name plus the value, in bytes. |
httpOnly | boolean | Whether JavaScript can't read the cookie (HttpOnly). |
secure | boolean | Whether the cookie is sent only over HTTPS. |
session | boolean | Whether it is a session cookie, with no fixed expiry. |
sameSite | string | Strict, Lax or None. Left out when the site didn't set it. |
priority | string | Low, Medium or High. |
sourceScheme | string | Scheme of the page that set it: Secure, NonSecure or Unset. |
sourcePort | integer | Port of the page that set it. -1 when unknown. |
There are two kinds of error. When the site answers with an error, or an action fails, the API still answers HTTP 200, and statusCode in the body tells you what happened. When your request itself can't be handled, you get an HTTP error status with a JSON body.
When the site answers the HTTP fetch with a status other than 2xx, or the browser load with 400 or more, the body has only request and statusCode, without outputs. To get the error page from the HTTP fetch, set httpResponseBodyOnError: true.
{
"request": { "url": "https://example.com/missing", "httpResponseBody": true, β¦ },
"statusCode": 404
}When an action fails, statusCode is 417 and message says which action failed and why.
{
"request": { "url": "https://example.com", "browserHtml": true, "actions": [ β¦ ] },
"statusCode": 417,
"message": "Could not not perform browser actions, error message: β¦"
}Neither case is charged.
These bodies have either an error string, or the same request, statusCode and message fields as above. None of them is charged.
| Status | When it happens | Example body | What to do |
|---|---|---|---|
| 400 | The request is invalid: the body isn't a JSON object; url is missing, not absolute, not http or https, or on a private network; no output flag is true; or imageSelector was sent without browserHtml: true. A field with the wrong type (for example "true" as a string) or an unknown value (for example "get" in lowercase) gets a 400 with a plain-text description. | | Fix the request using the message. Don't retry it unchanged. |
| 401 | The API key is missing, unknown or revoked, or it was created less than about 2 minutes ago. | | Check the x-api-key header or the Basic credentials, and copy the key again from the API key page. Wait a couple of minutes after creating a key. |
| 402 | Your balance is 0 credits, or your account is suspended. | | Check your balance on the Home page and add credits, or contact us. Requests work again within about 2 minutes of a top-up. |
| 404 | The path isn't /api/extract. | | Send POST to https://YOUR_API_URL/api/extract. |
| 413 | The request body is larger than 2 MiB. | | Send a smaller body, for example a shorter httpRequestText. |
| 415 | The request body is compressed (it has a Content-Encoding header). | | Send plain, uncompressed JSON. |
| 500 | The page couldn't be fetched or loaded (for example, the site couldn't be reached or the browser load failed), or an action is missing a required field (selector, or urlPattern) or has an invalid urlPattern. | | Check the actions first. Otherwise retry after a short wait; if it keeps failing for the same URL, contact us with the URL and the time. |
| 502 | The service couldn't be reached for a moment. | | Retry with an increasing wait (for example 1, 2, then 4 seconds). |
| 503 | Your key couldn't be checked for a moment. | | Retry after a few seconds. |
| 504 | The request took longer than the service's time limit. | | Make the request lighter: fewer or shorter actions, lower timeoutMs values, no full-page screenshot. Then retry. |
Requests are paid with prepaid credits. What a request costs depends only on its output flags:
| Request | Flags | Credits per request | $ per 1,000 |
|---|---|---|---|
| HTTP | httpResponseBody | 1 | $0.04 |
| Browser HTML | browserHtml | 9 | $0.36 |
| Screenshot | screenshot (with or without browserHtml) | 22 | $0.88 |
| HTTP + browser HTML | httpResponseBody + browserHtml | 10 | $0.40 |
| HTTP + screenshot | httpResponseBody + screenshot (with or without browserHtml) | 23 | $0.92 |
The other options (actions, cookies, images, headers and the screenshot options) don't change the price.
A request is charged only when the API answers HTTP 200 and the site answered with a 2xx status. You are not charged for:
statusCode of 300 or more, including the error pages you get with httpResponseBodyOnError;statusCode: 417);400, 401, 402, 404, 413, 415, 500, 502, 503 or 504.A 2xx answer is charged even if the page isn't what you hoped for, for example a "no results" page or a login page served with 200. Check the content, not only the status.
If your client disconnects or times out before the answer arrives, the request can still finish and be charged. Give your HTTP client a generous timeout (see Limits).
Charges appear in your dashboard shortly after each request: your balance on Home (your prices are in its Price list card), daily totals on Usage, and every top-up and day of usage on Credit history.
When your balance reaches 0, requests get 402 until credits are added. After a top-up, requests work again within about 2 minutes. Keep an eye on your balance so your jobs aren't interrupted.
http and https only, on public addresses.httpResponseBody fetch follows up to 10 redirects.timeoutMs, 30 seconds by default.504. Set your client's timeout to a few minutes.Each example comes in curl, Python (with requests) and Node.js 18 or later (with the built-in fetch, in an ES module). Replace https://YOUR_API_URL and YOUR_API_KEY with the values from your dashboard.
The fastest and cheapest request. Good for static HTML, JSON APIs and files.
curl -s -X POST https://YOUR_API_URL/api/extract \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com", "httpResponseBody": true}' \
-o response.json
# -e makes jq fail when the field is missing, so no file is written then.
if body=$(jq -er 'select(.statusCode >= 200 and .statusCode < 300) | .httpResponseBody' response.json); then
printf '%s' "$body" | base64 --decode > page.html
else
echo "No body:"; jq -c '{statusCode, message, error}' response.json
fiimport base64
import requests
API_URL = "https://YOUR_API_URL"
API_KEY = "YOUR_API_KEY"
resp = requests.post(
f"{API_URL}/api/extract",
headers={"x-api-key": API_KEY},
json={"url": "https://example.com", "httpResponseBody": True},
timeout=180,
)
resp.raise_for_status()
data = resp.json()
if 200 <= data["statusCode"] < 300:
# The body is the site's raw bytes (any charset or file type): save them as-is.
body = base64.b64decode(data["httpResponseBody"])
with open("page.html", "wb") as f:
f.write(body)
print("Saved", len(body), "bytes")
else:
print("The site answered", data["statusCode"])import { writeFile } from "node:fs/promises";
const API_URL = "https://YOUR_API_URL";
const API_KEY = "YOUR_API_KEY";
const resp = await fetch(`${API_URL}/api/extract`, {
method: "POST",
headers: { "x-api-key": API_KEY, "Content-Type": "application/json" },
body: JSON.stringify({ url: "https://example.com", httpResponseBody: true }),
signal: AbortSignal.timeout(180_000),
});
if (!resp.ok) throw new Error(`HTTP ${resp.status}: ${await resp.text()}`);
const data = await resp.json();
if (data.statusCode >= 200 && data.statusCode < 300) {
// The body is the site's raw bytes (any charset or file type): save them as-is.
const body = Buffer.from(data.httpResponseBody, "base64");
await writeFile("page.html", body);
console.log("Saved", body.length, "bytes");
} else {
console.log("The site answered", data.statusCode);
}For pages that build their content with JavaScript.
curl -s -X POST https://YOUR_API_URL/api/extract \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com", "browserHtml": true}' \
-o response.json
if html=$(jq -er 'select(.statusCode >= 200 and .statusCode < 300) | .browserHtml' response.json); then
printf '%s' "$html" | base64 --decode > rendered.html
else
echo "No HTML:"; jq -c '{statusCode, message, error}' response.json
fiimport base64
import requests
resp = requests.post(
"https://YOUR_API_URL/api/extract",
headers={"x-api-key": "YOUR_API_KEY"},
json={"url": "https://example.com", "browserHtml": True},
timeout=180,
)
resp.raise_for_status()
data = resp.json()
if 200 <= data["statusCode"] < 300:
html = base64.b64decode(data["browserHtml"]).decode("utf-8") # always UTF-8
print(data["finalUrl"], len(html))
else:
print("No HTML. statusCode:", data["statusCode"], data.get("message", ""))const resp = await fetch("https://YOUR_API_URL/api/extract", {
method: "POST",
headers: { "x-api-key": "YOUR_API_KEY", "Content-Type": "application/json" },
body: JSON.stringify({ url: "https://example.com", browserHtml: true }),
signal: AbortSignal.timeout(180_000),
});
if (!resp.ok) throw new Error(`HTTP ${resp.status}: ${await resp.text()}`);
const data = await resp.json();
if (data.statusCode >= 200 && data.statusCode < 300) {
const html = Buffer.from(data.browserHtml, "base64").toString("utf-8"); // always UTF-8
console.log(data.finalUrl, html.length);
} else {
console.log("No HTML. statusCode:", data.statusCode, data.message ?? "");
}A full-page screenshot saved to a file. The file is WebP unless the page is very tall, in which case it is PNG.
curl -s -X POST https://YOUR_API_URL/api/extract \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com", "screenshot": true, "screenshotFullPage": true, "screenshotQuality": 80}' \
-o response.json
# A missing screenshot (site error, or over the size limit) makes jq fail: no file is written.
if shot=$(jq -er 'select(.statusCode >= 200 and .statusCode < 300) | .screenshot' response.json); then
printf '%s' "$shot" | base64 --decode > screenshot.img
file screenshot.img # "Web/P image" or "PNG image data": rename to .webp or .png
else
echo "No screenshot:"; jq -c '{statusCode, message, error}' response.json
fiimport base64
import requests
resp = requests.post(
"https://YOUR_API_URL/api/extract",
headers={"x-api-key": "YOUR_API_KEY"},
json={
"url": "https://example.com",
"screenshot": True,
"screenshotFullPage": True,
"screenshotQuality": 80,
},
timeout=180,
)
resp.raise_for_status()
data = resp.json()
if not 200 <= data["statusCode"] < 300:
print("No screenshot. statusCode:", data["statusCode"], data.get("message", ""))
elif "screenshot" not in data:
print("The screenshot was over the size limit and was left out.")
else:
image = base64.b64decode(data["screenshot"])
ext = "png" if image.startswith(b"\x89PNG") else "webp"
with open(f"page.{ext}", "wb") as f:
f.write(image)
if data.get("screenshotTruncated"):
print("The page was taller than the capture limit and was cut off.")import { writeFile } from "node:fs/promises";
const resp = await fetch("https://YOUR_API_URL/api/extract", {
method: "POST",
headers: { "x-api-key": "YOUR_API_KEY", "Content-Type": "application/json" },
body: JSON.stringify({
url: "https://example.com",
screenshot: true,
screenshotFullPage: true,
screenshotQuality: 80,
}),
signal: AbortSignal.timeout(180_000),
});
if (!resp.ok) throw new Error(`HTTP ${resp.status}: ${await resp.text()}`);
const data = await resp.json();
if (data.statusCode < 200 || data.statusCode >= 300) {
console.log("No screenshot. statusCode:", data.statusCode, data.message ?? "");
} else if (!data.screenshot) {
console.log("The screenshot was over the size limit and was left out.");
} else {
const image = Buffer.from(data.screenshot, "base64");
const ext = image.subarray(0, 4).toString("latin1") === "\x89PNG" ? "png" : "webp";
await writeFile(`page.${ext}`, image);
if (data.screenshotTruncated) console.log("The page was cut off at the capture limit.");
}Search a site: wait for the search box, type, click the button, then wait for the results before the HTML is captured.
curl -X POST https://YOUR_API_URL/api/extract \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"url": "https://example.com/search",
"browserHtml": true,
"actions": [
{"action": "waitForSelector", "selector": {"type": "css", "value": "input[name=q]"}},
{"action": "type", "selector": {"type": "css", "value": "input[name=q]"}, "values": ["running shoes"]},
{"action": "click", "selector": {"type": "css", "value": "button[type=submit]"}},
{"action": "waitForSelector", "selector": {"type": "css", "value": ".results"}, "state": "visible", "timeoutMs": 15000}
]
}'import base64
import requests
def css(value):
return {"type": "css", "value": value}
payload = {
"url": "https://example.com/search",
"browserHtml": True,
"actions": [
{"action": "waitForSelector", "selector": css("input[name=q]")},
{"action": "type", "selector": css("input[name=q]"), "values": ["running shoes"]},
{"action": "click", "selector": css("button[type=submit]")},
{"action": "waitForSelector", "selector": css(".results"), "state": "visible", "timeoutMs": 15000},
],
}
resp = requests.post(
"https://YOUR_API_URL/api/extract",
headers={"x-api-key": "YOUR_API_KEY"},
json=payload,
timeout=180,
)
resp.raise_for_status()
data = resp.json()
if data["statusCode"] == 417:
print("An action failed:", data.get("message"))
elif "browserHtml" in data:
html = base64.b64decode(data["browserHtml"]).decode("utf-8")
print(html[:500])
else:
print("The site answered", data["statusCode"])const css = (value) => ({ type: "css", value });
const payload = {
url: "https://example.com/search",
browserHtml: true,
actions: [
{ action: "waitForSelector", selector: css("input[name=q]") },
{ action: "type", selector: css("input[name=q]"), values: ["running shoes"] },
{ action: "click", selector: css("button[type=submit]") },
{ action: "waitForSelector", selector: css(".results"), state: "visible", timeoutMs: 15000 },
],
};
const resp = await fetch("https://YOUR_API_URL/api/extract", {
method: "POST",
headers: { "x-api-key": "YOUR_API_KEY", "Content-Type": "application/json" },
body: JSON.stringify(payload),
signal: AbortSignal.timeout(180_000),
});
if (!resp.ok) throw new Error(`HTTP ${resp.status}: ${await resp.text()}`);
const data = await resp.json();
if (data.statusCode === 417) {
console.log("An action failed:", data.message);
} else if (data.browserHtml) {
console.log(Buffer.from(data.browserHtml, "base64").toString("utf-8").slice(0, 500));
} else {
console.log("The site answered", data.statusCode);
}Every output is base64. This example decodes the body, the browser HTML, the screenshot and the images, and saves them to files.
curl -s -X POST https://YOUR_API_URL/api/extract \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com", "httpResponseBody": true, "browserHtml": true, "imageSelector": "img"}' \
-o response.json
# Only fields that are present get a file (jq -e fails on a missing one).
for pair in httpResponseBody:body.bin browserHtml:rendered.html screenshot:screenshot.img; do
if b64=$(jq -er ".${pair%%:*}" response.json); then
printf '%s' "$b64" | base64 --decode > "${pair#*:}"
fi
done
jq -r '.images[]? | "\(.status) \(.url)"' response.jsonimport base64
import json
with open("response.json") as f:
data = json.load(f)
def save(field, filename):
if data.get(field):
with open(filename, "wb") as out:
out.write(base64.b64decode(data[field]))
save("httpResponseBody", "body.bin")
save("browserHtml", "rendered.html")
save("screenshot", "screenshot.img")
save("screenshotBrowserFrame", "screenshot-framed.img")
for image in data.get("images", []):
if image["status"] == "included":
ext = image["mimeType"].split("/")[-1]
with open(f"{image['sha256']}.{ext}", "wb") as out:
out.write(base64.b64decode(image["data"]))
else:
print("skipped", image["url"], image["status"])import { readFile, writeFile } from "node:fs/promises";
const data = JSON.parse(await readFile("response.json", "utf-8"));
async function save(field, filename) {
if (data[field]) await writeFile(filename, Buffer.from(data[field], "base64"));
}
await save("httpResponseBody", "body.bin");
await save("browserHtml", "rendered.html");
await save("screenshot", "screenshot.img");
await save("screenshotBrowserFrame", "screenshot-framed.img");
for (const image of data.images ?? []) {
if (image.status === "included") {
const ext = image.mimeType.split("/").pop();
await writeFile(`${image.sha256}.${ext}`, Buffer.from(image.data, "base64"));
} else {
console.log("skipped", image.url, image.status);
}
}401 with a key I just created.x-api-key, that the key has no extra spaces or quotes, and, with Basic authentication, that you encoded YOUR_API_KEY: (with the colon).402.httpResponseBody or browserHtml.statusCode: the site answered with an error. Set httpResponseBodyOnError: true to see the page it sent.statusCode: 417.message says which one and why. Check the selector in your own browser's developer tools, add a waitForSelector before the action, or raise timeoutMs.browserHtml is missing content I see in my browser.waitForSelector for an element of that content, or a waitForNetworkIdle, to your actions.httpResponseBody holds the bytes the site sent. Decode them with the charset in the content-type header (often UTF-8). browserHtml is always UTF-8.RIFF, PNG with \x89PNG. If screenshot is missing, it was over the size limit: lower screenshotQuality or screenshotDeviceScaleFactor, or turn off screenshotFullPage.