API Documentation

  • Home
  • API Documentation
image
image
image
image Developer Docs

Scraper API reference

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.

Overview

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).

Quick start

  1. 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.

  2. Check your credits. Requests are paid with credits, and your balance is on the Home page. With 0 credits, requests get 402.

  3. 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}'
  4. 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.

Authentication

Every request to /api/extract needs your API key. Send it in one of these two ways:

  • The x-api-key header (recommended): x-api-key: YOUR_API_KEY.
  • HTTP Basic authentication, with the key as the username or as the password. The other part can be empty. For example 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.

Request: POST /api/extract

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.

FieldTypeDefaultDescription
Outputs (choose at least one)
urlstringrequiredRequired. 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.
httpResponseBodybooleanfalseFetch the URL with a plain HTTP request. Returns the body in httpResponseBody and the response headers in httpResponseHeaders.
browserHtmlbooleanfalseLoad the URL in a browser, let its JavaScript run, perform your actions, and return the resulting HTML in browserHtml.
screenshotbooleanfalseReturn 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
customHttpRequestHeadersarrayβ€”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.
httpRequestMethodstring"GET"HTTP method for the httpResponseBody fetch: GET, POST, PUT, PATCH, DELETE or OPTIONS, in uppercase. The browser always loads the page with GET.
httpRequestTextstringβ€”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.
httpResponseBodyOnErrorbooleanfalseWhen 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
actionsarrayβ€”Steps to perform on the page after it loads, in order: wait for elements, click, type. See Actions.
responseCookiesbooleanfalseReturn the cookies the page set, in responseCookies.
Screenshot options
screenshotFullPagebooleanfalseCapture the whole height of the page instead of the visible 1920Γ—1080 area. Very tall pages are cut off; see screenshotTruncated.
screenshotQualityinteger60Image quality of screenshot, from 1 to 100. Higher means sharper and larger. Values outside the range are brought into it.
screenshotDeviceScaleFactorinteger1Pixel 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.
screenshotBrowserFramebooleanfalseAlso 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.
screenshotFramedFormatstring"webpNearLossless"Format of screenshotBrowserFrame: webpNearLossless (smaller and visually identical) or png (lossless).
Image extraction
imageSelectorstringβ€”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.
maxImageCountintegerβ€”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.
maxImageBytesintegerβ€”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.
maxTotalImageBytesintegerβ€”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

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 types

ActionWhat it doesFields it uses
waitForSelectorWaits until an element matching selector reaches state.selector, state, timeoutMs
clickClicks the element matching selector.selector, timeoutMs, actionabilityTimeoutMs, effectObservationMs, maxRetries
typeFocuses the field matching selector and types each string in values, in order.selector, values, timeoutMs, actionabilityTimeoutMs
waitForResponseWaits until the page receives a response whose URL matches urlPattern and whose status is in statusFilter.urlPattern, statusFilter, timeoutMs
waitForNetworkIdleWaits until the page has had no requests in progress for idleMs milliseconds.idleMs, timeoutMs

Action fields

FieldTypeDefaultDescription
actionstringrequiredRequired. One of the five action types above.
selectorobjectβ€”The element to act on: {"type": "css", "value": "#submit"}. value is a CSS selector and type is css. Required for waitForSelector, click and type.
valuesarray of stringsβ€”type only. The text to type, one string after another.
statestring"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.
urlPatternstringβ€”waitForResponse only, required. A regular expression matched against the full URL of each response.
statusFilterarray of integers2xxwaitForResponse only. The status codes that count, such as [200, 304]. Leave it out to accept any 2xx.
idleMsinteger500waitForNetworkIdle only. How long, in milliseconds, the page must go without requests in progress.
timeoutMsinteger30000How 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.
actionabilityTimeoutMsinteger3000click 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.
effectObservationMsinteger200click 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.
maxRetriesinteger3click 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 }
]

Response

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).

Example

{
  "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"
}

Response fields

FieldTypeDescription
requestobjectYour request, echoed back with the defaults filled in.
statusCodeintegerThe 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.
httpResponseBodystring (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.
browserHtmlstring (base64)Present when you set browserHtml. The page's HTML after it loaded and your actions ran, base64-encoded UTF-8.
httpResponseHeadersarrayThe site's response headers, as {"name": "…", "value": "…"} objects. Filled for the httpResponseBody fetch; an empty list when only the browser was used.
responseCookiesarrayPresent when you set responseCookies and the page set cookies. See Cookie fields.
screenshotstring (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.
screenshotBrowserFramestring (base64)Present when you set screenshot and screenshotBrowserFrame. The screenshot inside a browser-window frame, base64-encoded, in the format chosen with screenshotFramedFormat.
screenshotTruncatedbooleanPresent 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.
imagesarrayPresent when you sent imageSelector. One entry per distinct image; identical images appear once. See Image fields.
finalUrlstringThe URL after redirects. When the page was loaded in a browser, it also reflects redirects the page made itself.
capturedAtstringWhen the capture finished: UTC, ISO 8601 with nanoseconds, for example 2026-11-24T15:04:05.123456789Z.

Image fields

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).

FieldTypeDescription
urlstringThe image URL from the matching element: the version the page actually displayed.
finalUrlstringThe URL the image was finally served from, after redirects.
mimeTypestringThe image's content type, such as image/jpeg.
sizeBytesintegerSize of the original image, in bytes (before base64).
widthintegerWidth of the image, in pixels.
heightintegerHeight of the image, in pixels.
sha256stringLowercase hex SHA-256 of the original bytes. Identical images share it and appear only once.
statusstringWhether data is included, and why not when it isn't. See the values below.
datastring (base64)The original image bytes, base64-encoded. Present only when status is included.

Values of status

includedThe bytes are in data.
omitted_too_largeThe image is larger than maxImageBytes.
omitted_capThe image is past maxImageCount, or it would take the response past maxTotalImageBytes.
blocked_ssrfThe image's address is on a private or local network, so it was not returned.
fetch_failedThe page never loaded the image (for example, a lazy-loaded image that was never shown) or its download failed.
FieldTypeDescription
namestringCookie name.
valuestringCookie value.
domainstringDomain the cookie applies to, such as .example.com.
pathstringPath the cookie applies to.
expiresnumberExpiry as a Unix timestamp in seconds. -1 for a session cookie.
sizeintegerSize of the name plus the value, in bytes.
httpOnlybooleanWhether JavaScript can't read the cookie (HttpOnly).
securebooleanWhether the cookie is sent only over HTTPS.
sessionbooleanWhether it is a session cookie, with no fixed expiry.
sameSitestringStrict, Lax or None. Left out when the site didn't set it.
prioritystringLow, Medium or High.
sourceSchemestringScheme of the page that set it: Secure, NonSecure or Unset.
sourcePortintegerPort of the page that set it. -1 when unknown.

Errors

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.

Site errors and failed actions (HTTP 200)

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.

HTTP error statuses

These bodies have either an error string, or the same request, statusCode and message fields as above. None of them is charged.

StatusWhen it happensExample bodyWhat to do
400The 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.
{"error": "invalid input: 'url' is required"}

{"request": {…}, "statusCode": 400,
 "message": "URL scheme 'ftp' is not allowed; only http and https are accepted"}
Fix the request using the message. Don't retry it unchanged.
401The API key is missing, unknown or revoked, or it was created less than about 2 minutes ago.
{"error": "unauthorized: Missing or invalid Authorization header"}
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.
402Your balance is 0 credits, or your account is suspended.
{"error": "payment required: account 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.
404The path isn't /api/extract.
{"error": "not found"}
Send POST to https://YOUR_API_URL/api/extract.
413The request body is larger than 2 MiB.
{"error": "payload too large: body exceeds 2 MiB"}
Send a smaller body, for example a shorter httpRequestText.
415The request body is compressed (it has a Content-Encoding header).
{"error": "unsupported media type: Content-Encoding is not accepted, send an uncompressed JSON body"}
Send plain, uncompressed JSON.
500The 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.
{"request": {…}, "statusCode": 500, "message": "…"}
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.
502The service couldn't be reached for a moment.
{"error": "upstream HTTP error: connection or request failed"}
Retry with an increasing wait (for example 1, 2, then 4 seconds).
503Your key couldn't be checked for a moment.
{"error": "service unavailable: …"}
Retry after a few seconds.
504The request took longer than the service's time limit.
{"request": {…}, "statusCode": 504, "message": "request deadline of …s exceeded"}
Make the request lighter: fewer or shorter actions, lower timeoutMs values, no full-page screenshot. Then retry.

Credits and billing

Requests are paid with prepaid credits. What a request costs depends only on its output flags:

Pricing

RequestFlagsCredits per request$ per 1,000
HTTPhttpResponseBody1$0.04
Browser HTMLbrowserHtml9$0.36
Screenshotscreenshot (with or without browserHtml)22$0.88
HTTP + browser HTMLhttpResponseBody + browserHtml10$0.40
HTTP + screenshothttpResponseBody + screenshot (with or without browserHtml)23$0.92
  • 1 credit = $0.04 per 1,000 requests.
  • Only successful requests are charged: the request was processed and the site answered with a 2xx status.
  • Your exact rates, including any custom or volume pricing, are in the Price list card on the Home page of your dashboard.
  • Sending a lot of requests? Reach out for volume pricing.

The other options (actions, cookies, images, headers and the screenshot options) don't change the price.

What is charged

A request is charged only when the API answers HTTP 200 and the site answered with a 2xx status. You are not charged for:

  • site errors: a statusCode of 300 or more, including the error pages you get with httpResponseBodyOnError;
  • failed actions (statusCode: 417);
  • requests answered with an HTTP error status: 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).

Balance and running out

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.

Limits

  • Request body: up to 2 MiB of uncompressed JSON.
  • URLs: http and https only, on public addresses.
  • Redirects: the httpResponseBody fetch follows up to 10 redirects.
  • Actions: each wait gives up after timeoutMs, 30 seconds by default.
  • Screenshots: the visible area is 1920Γ—1080. Full-page captures stop at 20,000 pixels high or 30 million pixels in all. Captures over 16,383 pixels in either direction come back as PNG instead of WebP. A screenshot over the service's size limit is left out of the response.
  • Images: the number of images and their sizes are capped by the service; images over a cap are listed without their data.
  • Time: HTTP requests usually answer quickly. Browser requests, especially with actions or full-page screenshots, take longer. A request that runs past the service's time limit gets 504. Set your client's timeout to a few minutes.
  • Keys: a new key can take up to about 2 minutes to start working. Suspending or restoring an account takes about as long to apply.

Code examples

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.

Fetch a page over HTTP

The fastest and cheapest request. Good for static HTML, JSON APIs and files.

curl
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
fi
Python
import 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"])
Node.js
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);
}

Get the HTML after the browser renders it

For pages that build their content with JavaScript.

curl
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
fi
Python
import 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", ""))
Node.js
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 ?? "");
}

Take a screenshot

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
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
fi
Python
import 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.")
Node.js
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.");
}

Interact with the page using actions

Search a site: wait for the search box, type, click the button, then wait for the results before the HTML is captured.

curl
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}
    ]
  }'
Python
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"])
Node.js
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);
}

Decoding the response

Every output is base64. This example decodes the body, the browser HTML, the screenshot and the images, and saves them to files.

curl
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.json
Python
import 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"])
Node.js
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);
  }
}

Troubleshooting

I get 401 with a key I just created.
New keys can take up to about 2 minutes to start working. Also check that the header is exactly 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).
I get 402.
Your balance is 0 or your account is suspended. Check the Home page of your dashboard, add credits or contact us.
The HTTP status is 200, but there is no httpResponseBody or browserHtml.
Look at statusCode: the site answered with an error. Set httpResponseBodyOnError: true to see the page it sent.
I get statusCode: 417.
An action failed; 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.
The content loads after the page does. Add a waitForSelector for an element of that content, or a waitForNetworkIdle, to your actions.
The decoded text has strange characters.
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.
The screenshot won't open, or is missing.
Check the first bytes: WebP starts with RIFF, PNG with \x89PNG. If screenshot is missing, it was over the size limit: lower screenshotQuality or screenshotDeviceScaleFactor, or turn off screenshotFullPage.
My client timed out.
Browser requests can take a while. Raise your client's timeout to a few minutes. A request whose client gave up can still finish and be charged.