How to bypass captcha in Selenium: capture, solve, click
To bypass a captcha in Selenium, let the browser display the challenge, take a screenshot of its element, send that picture to a solver API and replay the answer with the Actions API. Selenium handles the capture, the coordinates and the mouse; the solver reads the image. This page explains the capture, the scale, the clicks and the slider, then gives the complete script in Python and in Node.js.
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 Selenium?
Wait until the challenge is visible, then ask Selenium for a screenshot of that element alone. In Python, WebDriverWait with visibility_of_element_located returns the element and screenshot_as_png gives the PNG bytes, which base64.b64encode turns into text. In Node.js, takeScreenshot returns the PNG already encoded in base64, ready for the image field of the task.
| Item | Python | Node.js |
|---|---|---|
| Runs on | Python 3.8 or newer | Node.js 18 or newer |
| Selenium | 4.6 or newer | 4.6 or newer |
| Install | pip install selenium |
npm i selenium-webdriver |
| Command | python solve_selenium.py |
node solve_selenium.js |
How do you click the points a solver returns in Selenium?
The solver returns points in pixels of the image it received. A screenshot is wider than the element on screen when the display has a pixel ratio above 1, so the example computes a scale: the width of the PNG, stored in bytes 16 to 20 of the file, divided by the width Selenium reports for the element. Each coordinate is divided by that scale before the click.
- The Actions API counts an offset from the centre of the element: the example subtracts half the width and half the height.
- Python:
move_to_element_with_offsetin ten steps, apauseafter each, thenclick. - Node.js:
movewithoriginset to the element, apause, thenclick.
How do you drag a slider captcha in Selenium?
A slider task, binance in the example, returns offset, a distance in pixels of the image. Divide it by the scale, then hold the handle and move it in 10 to 15 short steps instead of one jump, with a vertical drift of one or two pixels. In Python, click_and_hold grabs the handle, move_by_offset advances it with a pause after each step, and release drops it. In Node.js, press holds the button, each move starts from pointer, the current position, and release ends the drag.
Which browser and driver does the Selenium example start?
Google Chrome, in a visible window. webdriver.Chrome in Python and forBrowser with the value chrome in Node.js start the Chrome installed on the machine. Since Selenium 4.6, Selenium Manager finds or downloads the matching ChromeDriver by itself: there is no driver to install by hand and no path to set.
PAGE_URLis the page that shows the captcha.CAPTCHA_SELECTORis the CSS selector of the challenge element.- The wait for the element lasts up to 30 seconds in Python, 15 in Node.js.
quitcloses the browser and stops the driver.
What does a complete Selenium captcha script look like?
The two files below are complete scripts: 66 lines in Python, 53 in Node.js. Each one defines post and solve, opens the page, 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_selenium.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 selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
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")
driver = webdriver.Chrome()
driver.get(PAGE_URL)
captcha = WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.CSS_SELECTOR, CAPTCHA_SELECTOR)))
png = captcha.screenshot_as_png
image = base64.b64encode(png).decode()
width, height = captcha.size["width"], captcha.size["height"]
scale = struct.unpack(">I", png[16:20])[0] / width
solution = solve({"type": "aws-waf", "image": image})
actions = ActionChains(driver, duration=50)
last_x, last_y = width / 2, height / 2
for x, y in solution["points"]:
target_x, target_y = x / scale, y / scale
for step in range(1, 11):
dx = last_x + (target_x - last_x) * step / 10 - width / 2
dy = last_y + (target_y - last_y) * step / 10 - height / 2
actions.move_to_element_with_offset(captcha, round(dx), round(dy)).pause(random.uniform(0.05, 0.15))
actions.click()
last_x, last_y = target_x, target_y
actions.perform()
print(solution)
driver.quit()
solve_selenium.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 = driver.find_element(By.CSS_SELECTOR, SLIDER_SELECTOR)
offset = solve({"type": "binance", "image": base64.b64encode(slider.screenshot_as_png).decode()})["offset"] / scale
actions = ActionChains(driver, duration=50).click_and_hold(driver.find_element(By.CSS_SELECTOR, HANDLE_SELECTOR))
steps = random.randint(10, 15)
moved = 0
for step in range(1, steps + 1):
dx = round(offset * step / steps) - moved
actions.move_by_offset(dx, random.randint(-2, 2)).pause(random.uniform(0.05, 0.15))
moved += dx
actions.release().perform()
solve_selenium.js · Complete Node.js client: one createTask call, then getTaskResult until the task is ready (preview format).const { Builder, By, until } = require("selenium-webdriver");
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 driver = await new Builder().forBrowser("chrome").build();
await driver.get(PAGE_URL);
const el = await driver.wait(until.elementLocated(By.css(CAPTCHA_SELECTOR)), 15000);
await driver.wait(until.elementIsVisible(el), 15000);
const image = await el.takeScreenshot();
const rect = await el.getRect();
const scale = Buffer.from(image, "base64").readUInt32BE(16) / rect.width;
const solution = await solve({ type: "aws-waf", image });
for (const [x, y] of solution.points) {
const dx = Math.round(x / scale - rect.width / 2);
const dy = Math.round(y / scale - rect.height / 2);
await driver.actions({ async: true }).move({ origin: el, x: dx, y: dy, duration: 300 }).pause(100).click().perform();
await pause();
}
console.log(solution);
await driver.quit();
})();
solve_selenium.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 = await driver.wait(until.elementLocated(By.css(SLIDER_SELECTOR)), 15000);
const distance = (await solve({ type: "binance", image: await slider.takeScreenshot() })).offset / scale;
const handle = await driver.findElement(By.css(HANDLE_SELECTOR));
const steps = 10 + Math.floor(Math.random() * 6);
let drag = driver.actions({ async: true }).move({ origin: handle }).press();
let doneX = 0;
let doneY = 0;
for (let i = 1; i <= steps; i++) {
const targetX = Math.round((distance * i) / steps);
const targetY = i === steps ? 0 : Math.round(Math.random() * 4 - 2);
drag = drag.move({ origin: "pointer", x: targetX - doneX, y: targetY - doneY, duration: 50 + Math.floor(Math.random() * 100) });
doneX = targetX;
doneY = targetY;
}
await drag.pause(100).release().perform();
Captcha in Selenium: frequently asked questions
Can Selenium solve a captcha by itself?
No. Selenium drives a browser: it loads the page, takes screenshots and moves the mouse, but it does not read an image. The answer comes from a solver API: the script sends the screenshot of the challenge with createTask, waits for getTaskResult, then replays the points or the offset with the Actions API. Selenium needs no extra package for that: the Python example uses urllib from the standard library, the Node.js one the fetch function built into Node.js 18.
Why does a Selenium click land beside the target?
Two causes are common. The first is the scale: on a display with a pixel ratio of 2, the screenshot is twice as wide as the element, so every point must be divided by the PNG width over the element width. The second is the origin: in the Selenium versions the example targets, 4.6 or newer, move_to_element_with_offset counts from the centre of the element, not from its top left corner. The example subtracts half the width and half the height for that reason.
Does the Selenium example work with Firefox?
Yes. Replace webdriver.Chrome with webdriver.Firefox in Python, or the value given to forBrowser with firefox in Node.js, and Selenium Manager fetches geckodriver the same way it fetches ChromeDriver. The element screenshot and the Actions API are part of the WebDriver protocol, so the capture, the scale and the clicks stay as they are. Only the launch line changes.
Sources
The facts and figures quoted on this page come from these sources.
- Selenium, Actions API, Selenium documentation (mouse and pointer actions).
- Selenium, Selenium Manager, Selenium documentation (automatic driver management).