How to bypass captcha in Playwright: capture, solve, click
To bypass a captcha in Playwright, point a locator at the challenge, take its screenshot, send the picture to a solver API and replay the answer with the mouse of the page. Playwright waits for the element, captures it and reports its position; the solver returns where to click. This page explains the capture, the scale, the clicks and the slider, then gives the complete script in Node.js and Python.
Preview: the API described here is in public beta. Endpoint names, fields and codes can still change until the end of the beta, and no API key is distributed yet.
How do you capture the captcha element in Playwright?
With a locator. page.locator targets the challenge, waitFor in Node.js or wait_for in Python holds until it is visible, and the screenshot method of the locator captures that element alone, after scrolling it into view. It returns a Buffer in Node.js and bytes in Python. The bounding box is read after the capture, so its coordinates match the picture.
| Item | Node.js | Python |
|---|---|---|
| Runs on | Node.js 18 or newer | Python 3.8 or newer |
| Playwright | 1.40 or newer | 1.40 or newer |
| Install | npm i playwright |
pip install playwright |
| Command | node solve_playwright.js |
python solve_playwright.py |
How do you click the points a solver returns in Playwright?
Turn each point into page coordinates and send it to page.mouse. The scale is the PNG width, stored in bytes 16 to 20 of the file, divided by the width of the bounding box: readUInt32BE reads it in Node.js, struct.unpack in Python. A point then lands at the corner of the box plus x / and y /.
page.mouse.movewithstepsset to 20 draws the path in twenty moves.page.mouse.downandpage.mouse.uppress and release the button.- A random wait of 50 to 150 milliseconds separates the gestures:
pausein Node.js,time.sleepin Python.
How do you drag a slider captcha in Playwright?
Take a screenshot of the slider, submit it as a binance task and divide offset by the scale. Read the bounding box of the handle, move the mouse to its centre in 10 steps and call page.mouse.down. Then advance in 10 to 15 moves toward the target, each with a vertical shift of at most 2 pixels and a short wait, and finish with page.mouse.up. The Node.js block puts the last move back on the starting line; the Python block draws the shift with random.uniform on every step.
Which browser does the Playwright example launch?
The Google Chrome installed on the machine. chromium.launch receives channel with the value chrome and headless set to false, so Playwright drives the branded browser in a visible window instead of its bundled Chromium. With that channel, the example downloads no browser.
- Without
channel, Playwright starts its own Chromium, fetched withnpx playwright install chromiumin Node.js orplaywright install chromiumin Python. PAGE_URLandCAPTCHA_SELECTORname the page and the challenge element.browser.closeends the session.
What does a complete Playwright captcha script look like?
The two files below are complete scripts: 57 lines in Node.js, 60 in Python, the second written with the synchronous API. Each one defines post and solve, launches Chrome, captures the element, submits it as an aws-waf task and clicks the returned points. Under each file, a shorter block gives the lines to add for a slider. Replace YOUR_API_KEY, YOUR_API_URL, PAGE_URL and the selectors with your own values.
solve_playwright.js · Complete Node.js client: one createTask call, then getTaskResult until the task is ready (preview format).const { chromium } = require("playwright");
const API_KEY = "YOUR_API_KEY";
const BASE_URL = "YOUR_API_URL";
const PAGE_URL = "https://example.com/protected";
const CAPTCHA_SELECTOR = "#captcha-container";
const POLL_MS = 1500;
const TIMEOUT_MS = 120000;
async function post(route, body) {
const response = await fetch(BASE_URL + route, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ clientKey: API_KEY, ...body }),
});
const result = await response.json();
if (result.errorId) throw new Error(`${result.errorCode}: ${result.errorDescription}`);
return result;
}
async function solve(task) {
let result = await post("/createTask", { task });
if (result.status === "ready") return result.solution;
const taskId = result.taskId;
const deadline = Date.now() + TIMEOUT_MS;
while (Date.now() < deadline) {
await new Promise((resolve) => setTimeout(resolve, POLL_MS));
result = await post("/getTaskResult", { taskId });
if (result.status === "ready") return result.solution;
}
throw new Error(`task ${taskId} not ready after ${TIMEOUT_MS / 1000} s`);
}
const pause = () => new Promise((resolve) => setTimeout(resolve, 50 + Math.random() * 100));
(async () => {
const browser = await chromium.launch({ channel: "chrome", headless: false });
const page = await browser.newPage();
await page.goto(PAGE_URL);
const el = page.locator(CAPTCHA_SELECTOR);
await el.waitFor();
const png = await el.screenshot();
const box = await el.boundingBox();
const scale = png.readUInt32BE(16) / box.width;
const image = png.toString("base64");
const solution = await solve({ type: "aws-waf", image });
for (const [x, y] of solution.points) {
await page.mouse.move(box.x + x / scale, box.y + y / scale, { steps: 20 });
await pause();
await page.mouse.down();
await pause();
await page.mouse.up();
await pause();
}
console.log(solution);
await browser.close();
})();
solve_playwright.js · Lines to add to the Node.js example for a slider: same solve function, the handle is dragged over the returned distance.const SLIDER_SELECTOR = "#slider-captcha";
const HANDLE_SELECTOR = "#slider-handle";
const slider = page.locator(SLIDER_SELECTOR);
await slider.waitFor();
const sliderImage = (await slider.screenshot()).toString("base64");
const distance = (await solve({ type: "binance", image: sliderImage })).offset / scale;
const handleBox = await page.locator(HANDLE_SELECTOR).boundingBox();
const startX = handleBox.x + handleBox.width / 2;
const startY = handleBox.y + handleBox.height / 2;
const steps = 10 + Math.floor(Math.random() * 6);
await page.mouse.move(startX, startY, { steps: 10 });
await page.mouse.down();
for (let i = 1; i <= steps; i++) {
const jitter = i === steps ? 0 : Math.random() * 4 - 2;
await page.mouse.move(startX + (distance * i) / steps, startY + jitter);
await pause();
}
await page.mouse.up();
solve_playwright.py · Complete Python client: one createTask call, then getTaskResult until the task is ready (preview format).import base64
import json
import random
import struct
import time
import urllib.request
from playwright.sync_api import sync_playwright
API_KEY = "YOUR_API_KEY"
BASE_URL = "YOUR_API_URL"
PAGE_URL = "https://example.com/protected"
CAPTCHA_SELECTOR = "#captcha-container"
POLL_SECONDS = 1.5
TIMEOUT_SECONDS = 120
def post(route, body):
payload = json.dumps({"clientKey": API_KEY, **body}).encode()
request = urllib.request.Request(BASE_URL + route, payload, {"Content-Type": "application/json"})
with urllib.request.urlopen(request, timeout=30) as response:
result = json.load(response)
if result.get("errorId", 0) != 0:
raise RuntimeError(f"{result.get('errorCode')}: {result.get('errorDescription')}")
return result
def solve(task):
result = post("/createTask", {"task": task})
if result.get("status") == "ready":
return result["solution"]
task_id = result["taskId"]
deadline = time.monotonic() + TIMEOUT_SECONDS
while time.monotonic() < deadline:
time.sleep(POLL_SECONDS)
result = post("/getTaskResult", {"taskId": task_id})
if result.get("status") == "ready":
return result["solution"]
raise TimeoutError(f"task {task_id} not ready after {TIMEOUT_SECONDS} s")
with sync_playwright() as p:
browser = p.chromium.launch(channel="chrome", headless=False)
page = browser.new_page()
page.goto(PAGE_URL)
captcha = page.locator(CAPTCHA_SELECTOR)
captcha.wait_for(state="visible")
png = captcha.screenshot()
image = base64.b64encode(png).decode()
box = captcha.bounding_box()
scale = struct.unpack(">I", png[16:20])[0] / box["width"]
solution = solve({"type": "aws-waf", "image": image})
for x, y in solution["points"]:
page.mouse.move(box["x"] + x / scale, box["y"] + y / scale, steps=20)
time.sleep(random.uniform(0.05, 0.15))
page.mouse.down()
time.sleep(random.uniform(0.05, 0.15))
page.mouse.up()
print(solution)
browser.close()
solve_playwright.py · Lines to add to the Python example for a slider: same solve function, the handle is dragged over the returned distance.SLIDER_SELECTOR = "#slider-captcha"
HANDLE_SELECTOR = "#slider-handle"
slider = page.locator(SLIDER_SELECTOR)
offset = solve({"type": "binance", "image": base64.b64encode(slider.screenshot()).decode()})["offset"] / scale
handle = page.locator(HANDLE_SELECTOR).bounding_box()
start_x, start_y = handle["x"] + handle["width"] / 2, handle["y"] + handle["height"] / 2
page.mouse.move(start_x, start_y, steps=10)
page.mouse.down()
steps = random.randint(10, 15)
for step in range(1, steps + 1):
page.mouse.move(start_x + offset * step / steps, start_y + random.uniform(-2, 2))
time.sleep(random.uniform(0.05, 0.15))
page.mouse.up()
Captcha in Playwright: frequently asked questions
Can Playwright pass a captcha on its own?
No. Playwright automates the browser: navigation, screenshots, mouse and keyboard. Reading the challenge is the job of a solver API, which the example calls twice, with createTask then getTaskResult. The Node.js script uses the built-in fetch function and the Python script uses urllib from the standard library, so playwright is the only package to install. The solver answers with points to click or with an offset to drag.
Do I have to run playwright install before the example?
Not for the example as written. It launches the browser with the chrome channel, which means the Google Chrome already installed on the machine, so no browser is downloaded. The install command is needed only if you remove the channel to use the bundled Chromium, or switch to Firefox or WebKit. On a server without Chrome, either install Chrome or run playwright install chromium and drop the channel option.
Why capture with the locator instead of a full-page screenshot?
A locator screenshot contains the challenge and nothing else: the picture is smaller, the solver receives only what it must read, and the points it returns are counted from the top left corner of the element, which is also the origin given by the bounding box. With a screenshot of the whole page, you would have to crop the image or shift every point by the position of the element before clicking.
Does the Python example work with the asynchronous API?
Yes, with three changes. Import async_playwright instead of sync_playwright and await every call on the page, the locator and the mouse. Replace time.sleep with asyncio.sleep, so that the waits do not block the event loop. Run the solve function in a thread with asyncio.to_thread, because urllib is blocking, or rewrite post with an asynchronous HTTP client. The capture, the scale and the coordinates stay identical.
Sources
The facts and figures quoted on this page come from these sources.