By the end of this guide you will have a requests scraper that solves a widget CAPTCHA through the SurSolver API and posts the token with the form it belongs to — no browser open. The complete, runnable code is generated and embedded below, so this page spends its words on the two decisions that make or break an HTTP-client integration: which inputs you can read from HTML, and which ones only a live browser render can give you.
Where a CAPTCHA stops a scraper
A scraper meets a CAPTCHA in two places: a form whose submit needs a token (search, login, sign-up), or a page that serves a full-page challenge instead of content. This guide covers the first case. A challenge page (Cloudflare, Akamai SBSD, DataDome, PerimeterX, Vercel) is a different integration — the solver guides for each show the cookie-and-proxy flow — but the input question below applies to both.
On a form page the widget earns a token, and the form posts it under a field name: cf-turnstile-response for Turnstile, g-recaptcha-response for reCAPTCHA. Your job is to send the API the right inputs and attach the token to the request that submits the form.
Which inputs come from where
Every task type needs websiteURL (the URL the page actually sits at) plus its own values. Before you write a regex, check where each value lives:
| Input | Readable from fetched HTML | Only from a live browser |
|---|---|---|
websiteKey on a data-sitekey attribute |
Yes | — |
websiteKey when the widget is built by JavaScript |
The script URL may carry render=KEY |
Otherwise yes — the key appears in the DOM or network traffic only after render |
Turnstile action, cData |
Only if declared as data-* attributes |
Yes, when passed to turnstile.render() in page code |
reCAPTCHA v3 pageAction |
No | Yes — it is an argument of the page's grecaptcha.execute call |
Per-load values (Altcha challengeJSON, GeeTest challenge, Enterprise s) |
No | Yes — generated fresh on every render, short-lived |
Full-page-challenge inputs (pageData, captchaUrl, scriptUrl) |
Sometimes, from the block response | Safest captured from a real request cycle |
A regex over fetched HTML is fine for the first row and a trap for the rest. When the page builds its widget from JavaScript, open DevTools on a real load and take the value from the Elements or Network panel; how to identify any CAPTCHA lists the exact place per type. Values that change per load must be captured from a page you loaded moments before the task, never from an old session.
Python
This is the whole flow for a Turnstile form. It takes the site key, the form's post URL and its other fields from the constants at the top of the script, solves TurnstileTokenProxyLess, and posts the form with the token in cf-turnstile-response and the task's userAgent as the User-Agent header. SUCCESS_TEXT is the string that appears only in a response the site accepted — write that check for your own target, because it is the one part no generator can know.
# turnstile-python.py - solve Turnstile and post the token with the form.
# Install: pip install requests
# Run: python turnstile-python.py
import time
from urllib.parse import urlsplit
import requests
# Your SurSolver API key.
CLIENT_KEY = "sur_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
# The page that renders the widget, with its path and query string.
TARGET_URL = "https://example.com/page"
# data-sitekey on the .cf-turnstile element, or the sitekey of turnstile.render().
SITE_KEY = "YOUR_SITE_KEY"
# data-action on the same element; leave unset when it has none.
ACTION = None
# data-cdata on the same element; leave unset when it has none.
CDATA = None
# The User-Agent the solve runs with; send the result with this same user agent.
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36"
# Current application session as a Cookie header value; used on form submission.
SESSION_COOKIES = None
# Where the page posts the form (the form action, or the request in DevTools, Network).
FORM_URL = "https://example.com/submit"
# The form's other fields as a JSON object, such as {"username": "demo"}.
FORM_FIELDS = None
# Text that appears only in a response the site accepted.
SUCCESS_TEXT = "PASTE_ACCEPTED_MARKER"
API = "https://api.sursolver.com"
POLL_ATTEMPTS = 60
def call(path, body):
# API errors are HTTP 200 with errorId 1; anything else is a transport failure.
response = requests.post(f"{API}{path}", json=body, timeout=30)
response.raise_for_status()
data = response.json()
if data["errorId"] != 0:
raise RuntimeError(f'{data["errorCode"]}: {data["errorDescription"]}')
return data
def solve(task):
created = call("/createTask", {"clientKey": CLIENT_KEY, "task": task})
for _ in range(POLL_ATTEMPTS):
result = call("/getTaskResult", {"clientKey": CLIENT_KEY, "taskId": created["taskId"]})
if result["status"] == "ready":
return result["solution"]
time.sleep(3)
raise TimeoutError(f'task {created["taskId"]} was not ready in {POLL_ATTEMPTS} polls')
def without_empty(fields):
# Optional task fields are sent only when they have a value.
return {name: value for name, value in fields.items() if value not in (None, "")}
def main():
session = requests.Session()
if SESSION_COOKIES:
for part in SESSION_COOKIES.split(";"):
if "=" in part:
name, value = part.strip().split("=", 1)
session.cookies.set(name, value, domain=urlsplit(FORM_URL).hostname, path="/")
solution = solve({
"type": "TurnstileTokenProxyLess",
"websiteURL": TARGET_URL,
"websiteKey": SITE_KEY,
"userAgent": USER_AGENT,
**without_empty({
"action": ACTION,
"cData": CDATA,
}),
})
# The solve ran with USER_AGENT; the submit presents the same one.
headers = {"User-Agent": USER_AGENT}
# Send the token the way the page does; some sites name it differently or send JSON.
response = session.post(
FORM_URL,
data={**(FORM_FIELDS or {}), "cf-turnstile-response": solution["token"]},
headers=headers,
timeout=30,
)
session.close()
if not response.ok or SUCCESS_TEXT not in response.text:
raise SystemExit(f"The site did not accept the result (HTTP {response.status_code}).")
print("The site accepted the result.")
if __name__ == "__main__":
main()
Reading the script as a pattern:
- One page load to read, one request to submit. The scraper never renders the widget; it sends the parameters to the API and gets a token. That is why the inputs from the table above must be correct before
createTask— the API cannot see the page. - The task's required
userAgentis the identity of the solve and replay. The form post presents it as itsUser-Agentheader, so the request that consumes the token describes the same browser that earned it. - Poll, do not hammer. The generated client polls
getTaskResultevery 3 seconds, at most 60 times. API errors arrive as HTTP 200 witherrorId: 1; a non-200 status is a transport failure, not an answer about your task.
For reCAPTCHA v3 the same pattern posts g-recaptcha-response with the solution's gRecaptchaResponse, plus the form's regular fields, and pageAction in the task must match the page's execute call exactly. The reCAPTCHA v3 guide shows the verification side (action, hostname, score) as the site's server sees it.
Node.js
The same generated flow exists for Node: node turnstile-node.js — Node 18 or newer, no packages — posts the token in cf-turnstile-response with the form's other fields and the task's userAgent, reading every setting from the constants at the top.
// turnstile-node.js - solve Turnstile and post the token with the form.
// Install: Node.js 18 or newer (no packages).
// Run: node turnstile-node.js
const { setTimeout: sleep } = require('node:timers/promises');
// Your SurSolver API key.
const CLIENT_KEY = 'sur_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
// The page that renders the widget, with its path and query string.
const TARGET_URL = 'https://example.com/page';
// data-sitekey on the .cf-turnstile element, or the sitekey of turnstile.render().
const SITE_KEY = 'YOUR_SITE_KEY';
// data-action on the same element; leave unset when it has none.
const ACTION = '';
// data-cdata on the same element; leave unset when it has none.
const CDATA = '';
// The User-Agent the solve runs with; send the result with this same user agent.
const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36';
// Current application session as a Cookie header value; used on form submission.
const SESSION_COOKIES = '';
// Where the page posts the form (the form action, or the request in DevTools, Network).
const FORM_URL = 'https://example.com/submit';
// The form's other fields as a JSON object, such as {"username":"demo"}.
const FORM_FIELDS = undefined;
// Text that appears only in a response the site accepted.
const SUCCESS_TEXT = 'PASTE_ACCEPTED_MARKER';
const API = 'https://api.sursolver.com';
const POLL_ATTEMPTS = 60;
// API errors are HTTP 200 with errorId 1; anything else is a transport failure.
async function call(path, body) {
const res = await fetch(`${API}${path}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
if (data.errorId !== 0) throw new Error(`${data.errorCode}: ${data.errorDescription}`);
return data;
}
async function solve(task) {
const created = await call('/createTask', { clientKey: CLIENT_KEY, task });
for (let attempt = 0; attempt < POLL_ATTEMPTS; attempt += 1) {
const result = await call('/getTaskResult', {
clientKey: CLIENT_KEY,
taskId: created.taskId,
});
if (result.status === 'ready') return result.solution;
await sleep(3000);
}
throw new Error(`task ${created.taskId} was not ready in ${POLL_ATTEMPTS} polls`);
}
// Optional task fields are sent only when they have a value.
function withoutEmpty(fields) {
return Object.fromEntries(
Object.entries(fields).filter(([, value]) => value !== undefined && value !== ''),
);
}
async function main() {
const solution = await solve({
type: 'TurnstileTokenProxyLess',
websiteURL: TARGET_URL,
websiteKey: SITE_KEY,
userAgent: USER_AGENT,
...withoutEmpty({
action: ACTION,
cData: CDATA,
}),
});
// Send the token the way the page does; some sites name it differently or send JSON.
// The solve ran with USER_AGENT; the submit presents the same one.
const headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': USER_AGENT,
...(SESSION_COOKIES ? { Cookie: SESSION_COOKIES } : {}),
};
const body = new URLSearchParams({
...(FORM_FIELDS ?? {}),
['cf-turnstile-response']: solution.token,
});
const response = await fetch(FORM_URL, { method: 'POST', headers, body });
const text = await response.text();
if (!response.ok || !text.includes(SUCCESS_TEXT)) {
throw new Error(`The site did not accept the result (HTTP ${response.status}).`);
}
console.log('The site accepted the result.');
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
Keep the solve and the submit consistent
The task's proxy field is the exit IP the solve runs from. For types where the proxy is required (Cloudflare Challenge, Vercel, CaptchaFox, Akamai SBSD, DataDome, PerimeterX) or where you chose the proxy-capable task name on purpose, the request that carries the result must leave through the same proxy: set session.proxies to the same URL you sent in the task. For the proxyless names no proxy is involved at all. Proxies for CAPTCHA solving covers the formats and the sticky-session details.
Retries without paying for the same mistake twice
A task is charged when createTask accepts it, and a task that finishes as failed automatically returns its original charge once. Three rules follow:
- A refused submission (
ERROR_NO_SLOT_AVAILABLE) created nothing. Wait out the(retry in Ns)hint, add jitter, retry once. ERROR_FAILEDis final for that task. Start a new task, capped by your own attempt budget.- A task accepted but not ready after your polling budget was still charged. Check
getBalancebefore you decide to create another one.
The API has no endpoint for reporting a bad token, so keep your own count of rejected submissions per site; if a charge looks wrong, the billing guide explains what to send support.
Troubleshooting
| Symptom | Likely cause | Check |
|---|---|---|
ERROR_INVALID_REQUEST naming a field |
The errorDescription names it — usually an empty websiteKey because the regex matched nothing |
Fix the named field; nothing was charged |
ERROR_INVALID_REQUEST naming userAgent |
The required input is missing, blank, longer than 512 characters or not printable ASCII | Supply your browser's userAgent in the task and keep it on submission |
ERROR_ZERO_BALANCE |
No task was created | Top up the account, run again |
ERROR_TYPE_NOT_SUPPORTED |
The type name is misspelled or the proxyless/proxy form is wrong for that type |
Compare with the public catalog (GET /v1/task-types) |
| Site answers "captcha missing" | The form posts a different field name, or the page expects a callback-driven flow | Read the real field name from the form; the submit guide lists them per type |
| Token rejected, looks valid | Wrong variant (Enterprise vs standard), stale or reused token, or an input captured from an old page load | Re-capture per-load values, re-solve, submit immediately |
Start with one form
Run the embedded script against a form you are allowed to automate, with SUCCESS_TEXT taken from the page a passing submit lands on. The Playwright recipe is the same flow when a real browser must be in the loop, stop getting blocked while scraping covers what to do when responses turn hostile, and is web scraping legal lists the questions to answer before you scale up.