SurSolver

BlogPlaywright CAPTCHA Solving: An End-to-End Recipe

Playwright CAPTCHA Solving: An End-to-End Recipe

· Updated · 9 min read

This recipe builds one Playwright flow for Node.js around a widget CAPTCHA: the script opens the page, reads what the task needs, sends it to the SurSolver API, receives a token and puts it where the page expects it. The complete, runnable code is generated and embedded below — you do not retype a client — so this page concentrates on the parts that actually break in production: widgets that render late or inside frames, pages that re-render the widget, callbacks that submit by themselves, and submit clicks that race the callback.

The flow here applies a token to a form, as Cloudflare Turnstile and reCAPTCHA do; their solver guides (Turnstile, reCAPTCHA v3) list the task parameters. A cookie result follows a different path, shown in Cloudflare Challenge with Playwright, and so do request headers, in Kasada with Playwright.

The four beats of the flow

Every widget integration has the same shape, whether the widget is a Turnstile box or an invisible reCAPTCHA v3 score:

  1. Read. Open the page in a browser and collect the task inputs from the live DOM: websiteURL (the URL the page actually sits at, after redirects), the site key, and the per-render values the widget declares. How to identify any CAPTCHA lists where each type keeps them.
  2. Solve. createTask with those values, then poll getTaskResult every 3 seconds. The solve runs on the service side; your browser is not solving anything.
  3. Apply. Write the returned token into the field the form reads, call the callback the page registered, or both.
  4. Confirm. Wait for something that only appears after the site accepted the result — a logged-in header, a results list — and treat it as the only success signal.

The order matters because a token is single-use and short-lived: about two minutes for reCAPTCHA and about five for Turnstile, according to the vendors' documentation. Read first, solve second, submit immediately after the token arrives.

The generated script, beat by beat

The embedded script below is the whole flow for Turnstile. Its page read resolves on DOM content — busy pages never fire load — and then waits up to 10 seconds for a widget the page adds late. It reads data-sitekey, data-action and data-cdata from the .cf-turnstile element, solves a TurnstileTokenProxyLess task, then opens a fresh page that presents the userAgent supplied in the task, writes the token into cf-turnstile-response, calls the widget's named data-callback when one exists, clicks your SUBMIT_SELECTOR and waits for your SUCCESS_SELECTOR to appear. Point the four constants at the top of the script at your own page and run it.

turnstile-playwright.js
// turnstile-playwright.js - solve Turnstile on the live page and submit the form with the
// token.
// Install: npm install playwright && npx playwright install chromium
// Run: node turnstile-playwright.js

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

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 !== ''),
  );
}

// A value the page did not show must be pasted into its constant at the top.
function need(name, value) {
  if (value === undefined || value === null || value === '') {
    throw new Error(`Could not read ${name} from the page; fill in the ${name} constant.`);
  }
  return value;
}

// Opens the page once and reads what the solve needs from it.
async function readPage(browser) {
  const page = await browser.newPage({ userAgent: USER_AGENT });
  try {
    await page.goto(TARGET_URL, {
      waitUntil: 'domcontentloaded',
      timeout: 45000,
    });
    // The widget is often added after the page loads; give it a moment to appear.
    await page
      .waitForFunction(
        () =>
          !!document.querySelector('.cf-turnstile[data-sitekey]')?.dataset.sitekey,
        undefined,
        { timeout: 10000 },
      )
      .catch(() => undefined);
    const dom = await page.evaluate(() => ({
      websiteKey: document.querySelector('.cf-turnstile[data-sitekey]')?.dataset.sitekey,
      action: document.querySelector('.cf-turnstile')?.dataset.action,
      cData: document.querySelector('.cf-turnstile')?.dataset.cdata,
    }));
    return {
      pageUrl: page.url(),
      ...dom,
    };
  } finally {
    await page.close();
  }
}

async function main() {
  const browser = await chromium.launch();
  try {
    const found = await readPage(browser);
    const solution = await solve({
      type: 'TurnstileTokenProxyLess',
      websiteURL: found.pageUrl,
      websiteKey: need('websiteKey', SITE_KEY || found.websiteKey),
      userAgent: USER_AGENT,
      ...withoutEmpty({
        action: ACTION || found.action,
        cData: CDATA || found.cData,
      }),
    });

    // Submit from a fresh session with the user agent the solve ran with.
    const context = await browser.newContext({ userAgent: USER_AGENT });
    const page = await context.newPage();
    await page.goto(found.pageUrl);

    const applied = await page.evaluate(
      ({ token }) => {
        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;
      },
      { token: solution.token },
    );
    if (!applied) {
      throw new Error('The page has no token field or callback; check how it passes the token.');
    }

    await page.click(SUBMIT_SELECTOR);
    await page.locator(SUCCESS_SELECTOR).first().waitFor({ timeout: 15000 });
    console.log('The site accepted the token.');
  } finally {
    await browser.close();
  }
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

Three details in that script deserve attention before you adapt it:

  • The page is opened twice. The first pass reads parameters; the second pass, in a context created after the solve, replays the token with the user agent supplied in the task. A token applied to the same page instance that was open during the solve is fine too — the fresh context exists so the replay presents exactly the browser identity the solve used.
  • Optional values are sent only when present. action and cData go into the task only when the widget declares them; guessing them is worse than omitting them.
  • The callback runs in the page. page.evaluate calls window[callback](token) inside the page, so the page's own code — not your script — decides what happens next.

reCAPTCHA v3 has no widget box and no callback attribute. Its action is an argument of the page's own grecaptcha.execute(key, { action }) call, and a form field alone does not carry the score result — the page's script usually posts it. The generated script below reads the render= value from the api.js script URL, requires you to pass the page's PAGE_ACTION, and applies the token by overriding grecaptcha.execute so the page's own call sites receive the solved token, while also filling g-recaptcha-response for pages that post the field directly. This v3 flow is verified end to end against a live page whose server rejects invalid tokens: the site's own verdict accepted the solver's token.

recaptcha-v3-playwright.js
// recaptcha-v3-playwright.js - solve reCAPTCHA v3 on the live page and submit the form with the
// token.
// Install: npm install playwright && npx playwright install chromium
// Run: node recaptcha-v3-playwright.js

const { chromium } = require('playwright');
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';
// Optional, read from the page when empty: the render= value of the api.js or enterprise.js
// script URL.
const SITE_KEY = '';
// The action in the page's grecaptcha.execute(key, { action }) call.
const PAGE_ACTION = 'YOUR_PAGE_ACTION';
// Enterprise only: 0.3 or below answers fastest, higher runs a second execute.
const MIN_SCORE = undefined;
// 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 control that submits the form.
const SUBMIT_SELECTOR = '.PASTE_SUBMIT_SELECTOR';
// A selector that matches only after the site accepted the result.
const SUCCESS_SELECTOR = '.PASTE_ACCEPTED_SELECTOR';

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 !== ''),
  );
}

// A value the page did not show must be pasted into its constant at the top.
function need(name, value) {
  if (value === undefined || value === null || value === '') {
    throw new Error(`Could not read ${name} from the page; fill in the ${name} constant.`);
  }
  return value;
}

// Opens the page once and reads what the solve needs from it.
async function readPage(browser) {
  const page = await browser.newPage({ userAgent: USER_AGENT });
  try {
    await page.goto(TARGET_URL, {
      waitUntil: 'domcontentloaded',
      timeout: 45000,
    });
    // The widget is often added after the page loads; give it a moment to appear.
    await page
      .waitForFunction(
        () =>
          !!(() => {
            const src = [...document.scripts]
              .map((script) => script.src)
              .find((url) => /recaptcha\/(api|enterprise)\.js\?.*render=/.test(url));
            const key = src ? new URL(src).searchParams.get('render') : null;
            const fallback = document.querySelector('[data-sitekey]')?.dataset.sitekey;
            return key && key !== 'explicit' ? key : fallback;
          })(),
        undefined,
        { timeout: 10000 },
      )
      .catch(() => undefined);
    const dom = await page.evaluate(() => ({
      websiteKey: (() => {
        const src = [...document.scripts]
          .map((script) => script.src)
          .find((url) => /recaptcha\/(api|enterprise)\.js\?.*render=/.test(url));
        const key = src ? new URL(src).searchParams.get('render') : null;
        const fallback = document.querySelector('[data-sitekey]')?.dataset.sitekey;
        return key && key !== 'explicit' ? key : fallback;
      })(),
    }));
    return {
      pageUrl: page.url(),
      ...dom,
    };
  } finally {
    await page.close();
  }
}

async function main() {
  const browser = await chromium.launch();
  try {
    const found = await readPage(browser);
    const solution = await solve({
      type: 'ReCaptchaV3TokenProxyLess',
      websiteURL: found.pageUrl,
      websiteKey: need('websiteKey', SITE_KEY || found.websiteKey),
      pageAction: PAGE_ACTION,
      userAgent: USER_AGENT,
      ...withoutEmpty({
        minScore: MIN_SCORE,
      }),
    });

    // Submit from a fresh session with the user agent the solve ran with.
    const context = await browser.newContext({ userAgent: USER_AGENT });
    const page = await context.newPage();
    await page.goto(found.pageUrl);
    // reCAPTCHA defines execute() a moment after the page loads.
    await page.waitForFunction(
      () => typeof window.grecaptcha?.execute === 'function',
      undefined,
      { timeout: 15000 },
    );

    const applied = await page.evaluate(
      ({ token }) => {
        const api = window.grecaptcha;
        if (!api || typeof api.execute !== 'function') return false;
        // The page now receives the solved token wherever it calls execute().
        api.execute = () => Promise.resolve(token);
        for (const field of document.querySelectorAll('[name="g-recaptcha-response"]')) {
          field.value = token;
        }
        return true;
      },
      { token: solution.gRecaptchaResponse },
    );
    if (!applied) {
      throw new Error('The page has no reCAPTCHA API; check how it requests the token.');
    }

    await page.click(SUBMIT_SELECTOR);
    await page.locator(SUCCESS_SELECTOR).first().waitFor({ timeout: 15000 });
    console.log('The site accepted the token.');
  } finally {
    await browser.close();
  }
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

Both scripts end at the same place: your SUCCESS_SELECTOR proves the site accepted the result. An HTTP 200 on the form post does not.

When the widget is not where you expect

Widgets often render inside an iframe, and Turnstile additionally uses shadow DOM internally. The rule that keeps this simple: the task inputs live on the parent page, and the token goes back to the parent page. The site key, the action/cData attributes and the data-callback are attributes of the element the site author wrote, which is in the parent DOM. You rarely need to reach into the frame; when you do — for example to prove the widget finished rendering — Playwright's frameLocator reaches it:

solve.js
// Prove the widget frame rendered; the sitekey still comes from the parent element.
await page
  .frameLocator('iframe[src*="challenges.cloudflare.com"]')
  .locator('body')
  .waitFor({ state: 'visible', timeout: 15000 });

If document.querySelector('.cf-turnstile') finds nothing but the page clearly shows a widget, the site built the element from JavaScript after a route change or a user action. Trigger the action first, then read again; if it is built inside a shadow root, query through element.shadowRoot or let Playwright's locators pierce the shadow DOM for you. Where the parameters hide when the DOM shows nothing: the Network tab routes in identifying any CAPTCHA.

Re-renders and single-use tokens

A single-page application may rebuild the widget — and with it the site key's container and any callback binding — on every route change. Two consequences:

  • Re-read the parameters for every solve. A site key captured on /login is not guaranteed to be the one rendered after the app redirects you.
  • Never apply a token to a widget instance you are about to discard. If the page navigated between solve and apply, the element your selector matched may be a different render; re-locate it, apply, and submit in one tight sequence.

A token that sat through a re-render is usually still cryptographically valid but arrives at a page that has already moved on — the submit goes out without it, or with a field the new render emptied. If solves succeed but submissions look "missing the captcha", check the timeline: read, solve, apply, submit should be seconds apart, not minutes.

Callback and submit races

The most common double-failure in a Playwright flow is submitting twice or never:

  • A data-callback page submits itself. The function the site registered typically sends the form or an XHR when it receives the token. If your script also clicks submit, the second request carries a token that was already used, and the site answers timeout-or-duplicate or "captcha invalid". The generated scripts click submit after applying the token — for a callback page, drop the click and wait for the navigation or response the callback causes instead.
  • A field-only page needs your click. Writing cf-turnstile-response does not fire the page's own logic; the form waits for the user. Click submit yourself, and wait for the response you care about rather than a fixed sleep:
solve.js
// The page posts the form normally; wait for the request, not for a timer.
const [response] = await Promise.all([
  page.waitForResponse((res) => res.url().includes('/login'), { timeout: 15000 }),
  page.locator('button[type=submit]').click(),
]);
console.log('form POST answered', response.status());
  • Do not wait for networkidle. Analytics and websocket traffic keep the network busy forever on many sites; a waitUntil: 'networkidle' NavigationOptions line is a timeout generator, not a synchronization tool. Wait for the specific element, response or navigation you mean.
  • Confirm with the page, not the status code. A 200 response to a form post says the request arrived. The submit guide shows how to tell a field page from a callback page before you write either branch.

Headed or headless

chromium.launch({ headless: false }) is the better setting while you develop: you can watch the widget render and the form fill. Nothing in the API depends on the launch mode — the solve runs server-side, and only the token comes back; the required userAgent comes from your task input. Whether a particular target treats headless sessions differently is that site's decision; test both modes against your target instead of assuming.

Node.js

When the page's own form posts the token, the browser can drop out of the loop: node turnstile-node.js and node recaptcha-v3-node.js (Node 18 or newer, no packages) solve the task and post the form with the token in cf-turnstile-response or g-recaptcha-response, the form's other fields, and the task's required userAgent.

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;
});
recaptcha-v3-node.js
// recaptcha-v3-node.js - solve reCAPTCHA v3 and post the token with the form.
// Install: Node.js 18 or newer (no packages).
// Run: node recaptcha-v3-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';
// The render= value of the api.js or enterprise.js script URL.
const SITE_KEY = 'YOUR_SITE_KEY';
// The action in the page's grecaptcha.execute(key, { action }) call.
const PAGE_ACTION = 'YOUR_PAGE_ACTION';
// Enterprise only: 0.3 or below answers fastest, higher runs a second execute.
const MIN_SCORE = undefined;
// 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: 'ReCaptchaV3TokenProxyLess',
    websiteURL: TARGET_URL,
    websiteKey: SITE_KEY,
    pageAction: PAGE_ACTION,
    userAgent: USER_AGENT,
    ...withoutEmpty({
      minScore: MIN_SCORE,
    }),
  });

  // 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 ?? {}),
    ['g-recaptcha-response']: solution.gRecaptchaResponse,
  });
  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;
});

Python

pip install requests, then python turnstile-python.py or python recaptcha-v3-python.py, run the same two flows; acceptance is the success text in the response body — the confirm step of the recipe in plain HTTP form.

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()
recaptcha-v3-python.py
# recaptcha-v3-python.py - solve reCAPTCHA v3 and post the token with the form.
# Install: pip install requests
# Run: python recaptcha-v3-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"
# The render= value of the api.js or enterprise.js script URL.
SITE_KEY = "YOUR_SITE_KEY"
# The action in the page's grecaptcha.execute(key, { action }) call.
PAGE_ACTION = "YOUR_PAGE_ACTION"
# Enterprise only: 0.3 or below answers fastest, higher runs a second execute.
MIN_SCORE = 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": "ReCaptchaV3TokenProxyLess",
        "websiteURL": TARGET_URL,
        "websiteKey": SITE_KEY,
        "pageAction": PAGE_ACTION,
        "userAgent": USER_AGENT,
        **without_empty({
            "minScore": MIN_SCORE,
        }),
    })

    # 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 {}), "g-recaptcha-response": solution["gRecaptchaResponse"]},
        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()

Common failures

Symptom Likely cause Check
no site key found / Could not read websiteKey from the page Widget renders later, inside a frame or after a user action Raise the wait, trigger the action, or read the k/render= value from the Network tab
Solve succeeds, page says the captcha is missing Token went to a field the page ignores; the page waits for its callback Search the element for data-callback; see the submit guide for named and anonymous callbacks
Site answers timeout-or-duplicate or "captcha already used" The submit raced the callback, or the token was applied twice Keep exactly one submit path per flow; drop your click when a callback exists
Site rejects a token that looks valid Wrong variant (Enterprise vs standard, isInvisible missed) or a stale token Compare the script file and iframe URL with the checklist in the identify guide; re-solve instead of resubmitting
Second run of the same script fails The page re-rendered and the parameters changed Re-read data-sitekey/action on every run; they are not constants
ERROR_NO_SLOT_AVAILABLE from the API Submission refused at capacity; nothing was created or charged Wait out the (retry in Ns) hint; rate limits has the defaults

First run

Point TARGET_URL at a form you are allowed to automate and run the Turnstile script once end to end before adapting it. The quickstart shows the same two API calls without a browser, solving CAPTCHAs in a Python scraper covers the HTTP-client variant, and Selenium captcha solving does the same flow when WebDriver is what your codebase already uses.

More articles