SurSolver

BlogSelenium Captcha Solving with Python

Selenium Captcha Solving with Python

· Updated · 8 min read

Selenium drives the browser; it does not solve anything. The solve is two HTTP calls your script makes outside the page, and Selenium's job is the rest: read what the page declares, load the result into the session, and make the protected request. This post walks through three complete scenarios in Python — a Turnstile token on a form, the AWS WAF Challenge cookie, and Kasada request headers — and each embeds a generated, runnable script.

reCAPTCHA v2 is deliberately not one of them. Its guide stays open as reference material, but new Selenium work should start from the task types that are actively supported, and the three scenarios below cover the patterns every other type reuses: a token for a form field, a cookie for the session, and headers for a direct request.

How a Selenium solve is put together

Every scenario has the same four beats:

  1. Read. Open the page, wait for the widget or the protection script, and collect the task inputs: the page URL as the browser sees it, the site key from the DOM, or the loader script's URL from the network traffic.
  2. Solve. createTask with those inputs, then poll getTaskResult every 3 seconds until status is ready.
  3. Replay. Put the solution into the request that consumes it, presenting the browser identity the solve used. For a token or a cookie that is a fresh driver with the task's userAgent applied through the DevTools protocol; for a header solution it is an HTTP request whose headers come from the solution.
  4. Confirm. Wait for something only an accepted result produces: a selector that appears in the page, or text that appears in the response. HTTP 200 alone proves nothing.

The reading step is where Selenium-specific details live. The site key of a widget declared in HTML is a get_attribute('data-sitekey') away. A loader script such as Turnstile's api.js, AWS's challenge.js or Kasada's p.js never appears in the DOM — you read it from the performance log, which you must enable explicitly:

solve.py
options = webdriver.ChromeOptions()
options.set_capability("goog:loggingPrefs", {"performance": "ALL"})

def requested_urls(driver):
    urls = []
    for entry in driver.get_log("performance"):
        message = json.loads(entry["message"])["message"]
        if message["method"] == "Network.requestWillBeSent":
            urls.append(message["params"]["request"]["url"])
    return urls

Filter that list for the script your task type needs. The exact file name per type is in the checklist of how to identify any CAPTCHA.

Scenario 1: a token for the form (Turnstile)

The script reads data-sitekey, data-action and data-cdata from the .cf-turnstile element, solves a TurnstileTokenProxyLess task, opens a fresh driver that presents the task's userAgent, writes the token into cf-turnstile-response (and g-recaptcha-response, for pages wired in reCAPTCHA-compatible mode), invokes the widget's named callback when one is declared, clicks the submit control and waits for your success selector. Set TARGET_URL, SUBMIT_SELECTOR and SUCCESS_SELECTOR, run it, and watch the page confirm the submission.

turnstile-selenium.py
# turnstile-selenium.py - solve Turnstile on the live page and submit the form with the token.
# Install: pip install requests selenium
# Run: python turnstile-selenium.py

import time

import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait


# 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"
# Optional, read from the page when empty: data-sitekey on the .cf-turnstile element, or the
# sitekey of turnstile.render().
SITE_KEY = None
# Optional, read from the page when empty: data-action on the same element; leave unset when it
# has none.
ACTION = None
# Optional, read from the page when empty: 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"
# The control that submits the form.
SUBMIT_SELECTOR = ".PASTE_SUBMIT_SELECTOR"
# A selector that matches only after the site accepted the result.
SUCCESS_SELECTOR = ".PASTE_ACCEPTED_SELECTOR"


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 need(name, value):
    # A value the page did not show must be pasted into its constant at the top.
    if value in (None, ""):
        raise SystemExit(f"Could not read {name} from the page; fill in the {name} constant.")
    return value


def new_driver(user_agent=None):
    options = webdriver.ChromeOptions()
    options.add_argument("--headless=new")  # remove this line to watch the browser
    driver = webdriver.Chrome(options=options)
    if user_agent:
        # Present the user agent the solve ran with.
        driver.execute_cdp_cmd("Network.setUserAgentOverride", {"userAgent": user_agent})
    return driver


READ_SCRIPT = r"""
return {
  websiteKey: document.querySelector('.cf-turnstile[data-sitekey]')?.dataset.sitekey,
  action: document.querySelector('.cf-turnstile')?.dataset.action,
  cData: document.querySelector('.cf-turnstile')?.dataset.cdata,
};
"""

APPLY_SCRIPT = r"""
const [token] = arguments;
let filled = false;
for (const name of ['cf-turnstile-response', 'g-recaptcha-response']) {
  for (const field of document.querySelectorAll(`[name="${name}"]`)) {
    field.value = token;
    filled = true;
  }
}
const callback = document.querySelector('.cf-turnstile')?.dataset.callback;
if (callback && typeof window[callback] === 'function') {
  window[callback](token);
  filled = true;
}
return filled;
"""


def read_page():
    # Opens the page once and reads what the solve needs from its DOM.
    driver = new_driver(USER_AGENT)
    try:
        driver.get(TARGET_URL)
        found = driver.execute_script(READ_SCRIPT)
        found["pageUrl"] = driver.current_url
        return found
    finally:
        driver.quit()


def main():
    found = read_page()
    solution = solve({
        "type": "TurnstileTokenProxyLess",
        "websiteURL": found["pageUrl"],
        "websiteKey": need("websiteKey", SITE_KEY or found.get("websiteKey")),
        "userAgent": USER_AGENT,
        **without_empty({
            "action": ACTION or found.get("action"),
            "cData": CDATA or found.get("cData"),
        }),
    })

    # Submit from a fresh session with the user agent the solve ran with.
    driver = new_driver(USER_AGENT)
    try:
        driver.get(found["pageUrl"])
        applied = driver.execute_script(APPLY_SCRIPT, solution["token"])
        if not applied:
            raise SystemExit("The page has no token field or callback.")

        driver.find_element(By.CSS_SELECTOR, SUBMIT_SELECTOR).click()
        WebDriverWait(driver, 15).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, SUCCESS_SELECTOR))
        )
        print("The site accepted the token.")
    finally:
        driver.quit()


if __name__ == "__main__":
    main()

Two Selenium specifics worth knowing before you adapt it:

  • The token field is hidden. cf-turnstile-response (like g-recaptcha-response) is an <input type="hidden">, and WebDriver refuses to type into hidden elements. The script sets the value with execute_script, which is the reliable way for every hidden field.
  • The user agent override is a CDP call. driver.execute_cdp_cmd("Network.setUserAgentOverride", ...) applies to Chromium drivers; it is how the replay driver presents exactly the userAgent supplied in the task. Solve first, start the replay driver second — the order in the script is the order you need.

How to submit a CAPTCHA token explains why the script fills the field and calls the callback: the field is what a form post sends, the callback is what the page's own code waits for.

A silent AWS WAF Challenge answers with an interstitial or an x-amzn-waf-action: challenge response, not with a visible puzzle — Challenge is a different product from AWS WAF CAPTCHA, and the AwsChallengeCookie task refers to Challenge only. The generated script captures the page's challenge.js request from the performance log, solves with it as scriptUrl, then sets the returned token as the aws-waf-token cookie on the origin, reloads the protected page and waits for your success selector. Verified end to end against a live AWS WAF-protected site: without the cookie the protected URL serves a short stub, with it the full page.

aws-challenge-selenium.py
# aws-challenge-selenium.py - solve AWS Challenge and open the protected page with the
# aws-waf-token cookie.
# Install: pip install requests selenium
# Run: python aws-challenge-selenium.py

import json
import re
import time
from urllib.parse import urlsplit

import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait


# Your SurSolver API key.
CLIENT_KEY = "sur_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
# The protected page that answers with the challenge.
TARGET_URL = "https://example.com/page"
# Optional, read from the page when empty: the challenge.js request of the challenged page
# (DevTools, Network).
SCRIPT_URL = 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"
# A selector that matches only after the site accepted the result.
SUCCESS_SELECTOR = ".PASTE_ACCEPTED_SELECTOR"


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 new_driver(user_agent=None):
    options = webdriver.ChromeOptions()
    options.add_argument("--headless=new")  # remove this line to watch the browser
    options.set_capability("goog:loggingPrefs", {"performance": "ALL"})
    driver = webdriver.Chrome(options=options)
    if user_agent:
        # Present the user agent the solve ran with.
        driver.execute_cdp_cmd("Network.setUserAgentOverride", {"userAgent": user_agent})
    return driver


def need(name, value):
    # A value the page did not show must be pasted into its constant at the top.
    if value in (None, ""):
        raise SystemExit(f"Could not read {name} from the page; fill in the {name} constant.")
    return value


def requested_urls(driver):
    # URLs the page requested, from the browser performance log.
    urls = []
    for entry in driver.get_log("performance"):
        message = json.loads(entry["message"])["message"]
        if message["method"] == "Network.requestWillBeSent":
            urls.append(message["params"]["request"]["url"])
    return urls


def read_page():
    # Opens the page once and reads what the solve needs from it.
    driver = new_driver(USER_AGENT)
    try:
        driver.get(TARGET_URL)
        time.sleep(3)
        pattern = re.compile(r"\/challenge\.js(\?|$)")
        urls = [url for url in requested_urls(driver) if pattern.search(url)]
        return {"pageUrl": driver.current_url, "scriptUrl": urls[0] if urls else None}
    finally:
        driver.quit()


def main():
    found = read_page()
    solution = solve({
        "type": "AwsChallengeCookie",
        "websiteURL": found["pageUrl"],
        "scriptUrl": need("scriptUrl", SCRIPT_URL or found.get("scriptUrl")),
        "userAgent": USER_AGENT,
    })

    # Replay with the user agent the solve ran with.
    driver = new_driver(USER_AGENT)
    try:
        parts = urlsplit(found["pageUrl"])
        # A cookie can only be set for the page that is open: load the origin first.
        driver.get(f"{parts.scheme}://{parts.netloc}/")
        cookies = {
            **solution.get("cookies", {}),
            "aws-waf-token": solution["aws-waf-token"],
        }
        for name, value in cookies.items():
            driver.add_cookie({"name": name, "value": value, "path": "/", "secure": True})
        driver.get(found["pageUrl"])
        WebDriverWait(driver, 15).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, SUCCESS_SELECTOR))
        )
        print("The site served the protected page.")
    finally:
        driver.quit()


if __name__ == "__main__":
    main()

What to watch:

  • scriptUrl is the page's own request, copied with its query string. A guessed loader path or a script from a different site describes an integration that does not exist; the task rejects it.
  • A cookie needs its origin open. WebDriver only sets a cookie for the domain of the current page, so the script navigates to the origin root first, calls add_cookie, then loads the protected URL. Doing it in the other order answers invalid cookie domain.
  • This task needs no proxy, and the result is the cookie value in aws-waf-token; the required userAgent comes from your task input. The cookie carries the WAF challenge completion — it is not a login session, and the protected request keeps its own authentication.

Scenario 3: headers on a direct request (Kasada)

Kasada does not produce a form field or a cookie. The solution is a set of request headers: token goes on the wire as x-kpsdk-ct, kpsdkCd as x-kpsdk-cd, plus x-kpsdk-h and x-kpsdk-v when the solution carries them, with the solution's User-Agent and Accept-Language. The generated script uses Selenium only to read: it opens the page once, takes the site's p.js request from the performance log, and solves a KasadaTokenProxyLess task. The replay is an HTTP client — requests, not the browser — sending your protected request with the header map attached. A replay that navigates a browser is rejected by Kasada, which is why the headers travel on a plain request: API_URL is the protected endpoint, API_METHOD and API_BODY carry a non-GET call, and the optional API_HEADERS constant (a JSON object) adds the app-specific headers the endpoint needs on top. This flow is verified end to end against a live Kasada-protected site: the solver's headers turn the 429 block page into the real response.

kasada-selenium.py
# kasada-selenium.py - solve Kasada and send the protected request with the returned headers.
# Install: pip install requests selenium
# Run: python kasada-selenium.py

import json
import re
import time

import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait


# Your SurSolver API key.
CLIENT_KEY = "sur_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
# The page that starts the protected action.
TARGET_URL = "https://example.com/page"
# Optional, read from the page when empty: the p.js request of the page that starts the
# protected action.
SCRIPT_URL = 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"
# The protected request the page makes after Kasada ran.
API_URL = "https://example.com/api/endpoint"
# Its HTTP method; GET when unset.
API_METHOD = None
# Its JSON body for POST, PUT and PATCH requests.
API_BODY = None
# Other headers the protected request needs, as a JSON object, such as {"x-app-id":"web"}.
API_HEADERS = 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 new_driver(user_agent=None):
    options = webdriver.ChromeOptions()
    options.add_argument("--headless=new")  # remove this line to watch the browser
    options.set_capability("goog:loggingPrefs", {"performance": "ALL"})
    driver = webdriver.Chrome(options=options)
    if user_agent:
        # Present the user agent the solve ran with.
        driver.execute_cdp_cmd("Network.setUserAgentOverride", {"userAgent": user_agent})
    return driver


def need(name, value):
    # A value the page did not show must be pasted into its constant at the top.
    if value in (None, ""):
        raise SystemExit(f"Could not read {name} from the page; fill in the {name} constant.")
    return value


def requested_urls(driver):
    # URLs the page requested, from the browser performance log.
    urls = []
    for entry in driver.get_log("performance"):
        message = json.loads(entry["message"])["message"]
        if message["method"] == "Network.requestWillBeSent":
            urls.append(message["params"]["request"]["url"])
    return urls


def read_page():
    # Opens the page once and reads what the solve needs from it.
    driver = new_driver(USER_AGENT)
    try:
        driver.get(TARGET_URL)
        time.sleep(3)
        pattern = re.compile(r"\/p\.js(\?|$)")
        urls = [url for url in requested_urls(driver) if pattern.search(url)]
        return {"pageUrl": driver.current_url, "scriptUrl": urls[0] if urls else None}
    finally:
        driver.quit()


def main():
    found = read_page()
    solution = solve({
        "type": "KasadaTokenProxyLess",
        "websiteURL": found["pageUrl"],
        "scriptUrl": need("scriptUrl", SCRIPT_URL or found.get("scriptUrl")),
        "userAgent": USER_AGENT,
    })

    headers = {
        **(API_HEADERS or {}),
        "x-kpsdk-ct": solution["token"],
        "x-kpsdk-cd": solution["kpsdkCd"],
        "User-Agent": USER_AGENT,
        "Accept-Language": solution["acceptLanguage"],
    }
    # The challenge returns these two only when the site uses them.
    if solution.get("kpsdkH"):
        headers["x-kpsdk-h"] = solution["kpsdkH"]
    if solution.get("kpsdkV"):
        headers["x-kpsdk-v"] = solution["kpsdkV"]
    # The headers are not bound to a page: send the request with an HTTP client.
    if API_BODY:
        headers["Content-Type"] = "application/json"
    response = requests.request(
        (API_METHOD or "GET").upper(),
        API_URL,
        headers=headers,
        data=API_BODY,
        timeout=30,
    )
    if not response.ok or SUCCESS_TEXT not in response.text:
        raise SystemExit(
            f"The site did not accept the headers (HTTP {response.status_code}).",
        )
    print("The site accepted the headers.")


if __name__ == "__main__":
    main()

The details that decide whether this works:

  • The header names are the solution's keys. solution["token"] is not a page token; it is the x-kpsdk-ct value. Sending it as a cookie or a form field goes nowhere.
  • Language travels with the identity. acceptLanguage is part of the solution because the request that carries the headers should present the same language the solve did. Drop it and the mismatch is visible to the site.
  • No proxy field goes in the task. Kasada runs without a caller proxy; the replay happens from your own client.

Shape's headers follow the same pattern with its own header names, and Akamai's _abck sits between scenarios 2 and 3: cookies replayed with the task's user agent. The solver guides for Kasada, Shape and Akamai show each contract.

Node.js

All three scenarios also run without a browser: node turnstile-node.js, node aws-challenge-node.js and node kasada-node.js (Node 18 or newer, no packages) take the loader URLs and keys as constants at the top instead of reading a performance log, then apply the result to their own request — the token with the form, the cookie on the protected request, the headers on the protected call.

turnstile-node.js
// 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;
});
aws-challenge-node.js
// aws-challenge-node.js - solve AWS Challenge and request the protected page with the
// aws-waf-token cookie.
// Install: Node.js 18 or newer (no packages).
// Run: node aws-challenge-node.js

const { setTimeout: sleep } = require('node:timers/promises');

// Your SurSolver API key.
const CLIENT_KEY = 'sur_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
// The protected page that answers with the challenge.
const TARGET_URL = 'https://example.com/page';
// The challenge.js request of the challenged page (DevTools, Network).
const SCRIPT_URL = 'https://example.com/challenge.js';
// 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';
// 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 !== ''),
  );
}

function cookieHeader(cookies) {
  return Object.entries(cookies)
    .map(([name, value]) => `${name}=${value}`)
    .join('; ');
}

async function main() {
  const solution = await solve({
    type: 'AwsChallengeCookie',
    websiteURL: TARGET_URL,
    scriptUrl: SCRIPT_URL,
    userAgent: USER_AGENT,
  });

  const cookies = {
    ...(solution.cookies ?? {}),
    'aws-waf-token': solution['aws-waf-token'],
  };
  // Replay with the user agent the solve ran with.
  const headers = {
    Cookie: cookieHeader(cookies),
    'User-Agent': USER_AGENT,
  };
  const response = await fetch(TARGET_URL, { headers });
  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;
});
kasada-node.js
// kasada-node.js - solve Kasada and send the protected request with the returned headers.
// Install: Node.js 18 or newer (no packages).
// Run: node kasada-node.js

const { setTimeout: sleep } = require('node:timers/promises');

// Your SurSolver API key.
const CLIENT_KEY = 'sur_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
// The page that starts the protected action.
const TARGET_URL = 'https://example.com/page';
// The p.js request of the page that starts the protected action.
const SCRIPT_URL = 'https://example.com/challenge.js';
// 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';
// The protected request the page makes after Kasada ran.
const API_URL = 'https://example.com/api/endpoint';
// Its HTTP method; GET when unset.
const API_METHOD = '';
// Its JSON body for POST, PUT and PATCH requests.
const API_BODY = '';
// Other headers the protected request needs, as a JSON object, such as {"x-app-id":"web"}.
const API_HEADERS = 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: 'KasadaTokenProxyLess',
    websiteURL: TARGET_URL,
    scriptUrl: SCRIPT_URL,
    userAgent: USER_AGENT,
  });

  const headers = {
    ...(API_HEADERS ?? {}),
    'x-kpsdk-ct': solution.token,
    'x-kpsdk-cd': solution.kpsdkCd,
    'User-Agent': USER_AGENT,
    'Accept-Language': solution.acceptLanguage,
  };
  // The challenge returns these two only when the site uses them.
  if (solution.kpsdkH) headers['x-kpsdk-h'] = solution.kpsdkH;
  if (solution.kpsdkV) headers['x-kpsdk-v'] = solution.kpsdkV;
  if (API_BODY) headers['Content-Type'] = 'application/json';
  const response = await fetch(API_URL, {
    method: (API_METHOD || 'GET').toUpperCase(),
    headers,
    ...(API_BODY ? { body: API_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;
});

Python

pip install requests, then python turnstile-python.py, python aws-challenge-python.py or python kasada-python.py behave identically, each judging acceptance by the response body rather than the status code.

turnstile-python.py
# 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()
aws-challenge-python.py
# aws-challenge-python.py - solve AWS Challenge and request the protected page with the
# aws-waf-token cookie.
# Install: pip install requests
# Run: python aws-challenge-python.py

import time

import requests


# Your SurSolver API key.
CLIENT_KEY = "sur_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
# The protected page that answers with the challenge.
TARGET_URL = "https://example.com/page"
# The challenge.js request of the challenged page (DevTools, Network).
SCRIPT_URL = "https://example.com/challenge.js"
# 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"
# 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 main():
    solution = solve({
        "type": "AwsChallengeCookie",
        "websiteURL": TARGET_URL,
        "scriptUrl": SCRIPT_URL,
        "userAgent": USER_AGENT,
    })

    # Replay with the user agent the solve ran with.
    headers = {"User-Agent": USER_AGENT}
    cookies = {
        **solution.get("cookies", {}),
        "aws-waf-token": solution["aws-waf-token"],
    }
    response = requests.get(
        TARGET_URL,
        headers=headers,
        cookies=cookies,
        timeout=30,
    )
    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()
kasada-python.py
# kasada-python.py - solve Kasada and send the protected request with the returned headers.
# Install: pip install requests
# Run: python kasada-python.py

import time

import requests


# Your SurSolver API key.
CLIENT_KEY = "sur_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
# The page that starts the protected action.
TARGET_URL = "https://example.com/page"
# The p.js request of the page that starts the protected action.
SCRIPT_URL = "https://example.com/challenge.js"
# 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"
# The protected request the page makes after Kasada ran.
API_URL = "https://example.com/api/endpoint"
# Its HTTP method; GET when unset.
API_METHOD = None
# Its JSON body for POST, PUT and PATCH requests.
API_BODY = None
# Other headers the protected request needs, as a JSON object, such as {"x-app-id":"web"}.
API_HEADERS = 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 main():
    solution = solve({
        "type": "KasadaTokenProxyLess",
        "websiteURL": TARGET_URL,
        "scriptUrl": SCRIPT_URL,
        "userAgent": USER_AGENT,
    })

    headers = {
        **(API_HEADERS or {}),
        "x-kpsdk-ct": solution["token"],
        "x-kpsdk-cd": solution["kpsdkCd"],
        "User-Agent": USER_AGENT,
        "Accept-Language": solution["acceptLanguage"],
    }
    # The challenge returns these two only when the site uses them.
    if solution.get("kpsdkH"):
        headers["x-kpsdk-h"] = solution["kpsdkH"]
    if solution.get("kpsdkV"):
        headers["x-kpsdk-v"] = solution["kpsdkV"]
    cookies = None
    if API_BODY:
        headers["Content-Type"] = "application/json"
    response = requests.request(
        (API_METHOD or "GET").upper(),
        API_URL,
        headers=headers,
        data=API_BODY,
        cookies=cookies,
        timeout=30,
    )
    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()

Common failures

Symptom Likely cause Check
ElementNotInteractableException on the token field The field is hidden Set the value with execute_script, never send_keys
invalid cookie domain from add_cookie The driver was not on the cookie's domain Open the origin first, then set cookies, then navigate
get_log("performance") returns nothing relevant The capability was not set before the driver started goog:loggingPrefs: {"performance": "ALL"} must be on the options of the driver that loads the page
The site says the captcha is missing after submit The page waits for its callback, or the field name differs Search the widget element for data-callback; read the real field name from the form
Solve succeeds, replay refused The replay presented a different user agent, or a token was reused late Replay in a fresh driver with task["userAgent"], submit immediately, never resubmit an old token
timeout-or-duplicate from the site The form was submitted twice, or the token expired Keep one submit path: a callback page submits itself, so drop your click

Start with the Turnstile script

Run the Turnstile script against a form you own first; it exercises the full read–solve–replay loop with the least moving parts. The quickstart documents createTask and getTaskResult themselves, the Playwright recipe is the same flow when your stack is Node.js, and solving CAPTCHAs in a Python scraper covers the no-browser variant.

More articles