Selenium and reCAPTCHA: waiting for the token without flaky retries
You click the checkbox, the spinner does its little dance, and your Selenium test sits there hoping that a token appears. If the wait is too short, the form submits with an empty g-recaptcha-response. If it is too long, the suite crawls. Both outcomes come from the same mistake: the test is waiting on the wrong thing.
Why fixed sleeps make the suite flaky
A reCAPTCHA v2 widget is not a normal input. The checkbox only proves that a user interacted with the widget. The actual proof is the token that Google drops into a hidden textarea, usually textarea#g-recaptcha-response. That token is what your form sends to the server.
The problem is timing. Sometimes the checkbox fills the textarea in half a second. Sometimes a challenge is shown and the same step takes ten seconds. Sometimes the token never arrives because the browser environment looks suspicious. A fixed time.sleep(10) is a bet, and it loses in both directions: short sleeps fail on slow runs, long sleeps make every run slower.
A WebDriverWait aimed at the textarea feels more precise, but it is still flaky. The textarea exists from the start and may be empty for a long time, so waiting for its presence proves nothing. Waiting for its value to become non-empty can work, yet it mixes two concerns: the test is polling a DOM side effect while the token is produced somewhere else. If the token expires before submission, the test can even pass locally and fail in CI.
There is a cleaner approach: do not wait for the DOM at all. Solve the captcha through an API first, poll that API for the token, and inject the token into the page. The wait becomes deterministic because it is tied to a server-side status, not to a widget animation.
Solve the captcha outside the browser
NeuroCaptcha exposes a createTask method that accepts a RecaptchaV2TaskProxyless task. Send the page URL and the site key, and the service returns a taskId while the price is held, not charged.
{
"clientKey": "YOUR_API_KEY",
"task": {
"type": "RecaptchaV2TaskProxyless",
"websiteURL": "https://www.google.com/recaptcha/api2/demo",
"websiteKey": "6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-"
}
}
You find the site key in the widget's data-sitekey attribute or in the k parameter of the anchor request in DevTools. If the page shows only a badge, set isInvisible: true. For widgets loaded from www.recaptcha.net you can pass apiDomain. If your browser sends a custom User-Agent, pass it as userAgent so the service returns the token with that value.
Then poll getTaskResult every two seconds. When status becomes ready, the token is in solution.gRecaptchaResponse. The response also carries cost, ip, and solveCount, so you can log exactly what happened. This polling loop is the only wait that matters, and it is bounded by a deadline rather than by a blind guess. A failed task costs nothing and returns an error code, which makes it safe to create a fresh task and try again. The proxyless v2 type costs $0.0006 per solved task, so one clean retry is cheaper than a red build.
Waiting in Selenium without retries
The Selenium side becomes a three-step script: read the site key from the live page, wait for the API token, then inject the token and submit.
from selenium import webdriver
import requests, time, os
API = "https://api.neurocaptcha.com"
KEY = os.environ["API_KEY"]
driver = webdriver.Chrome()
driver.get("https://www.google.com/recaptcha/api2/demo")
sitekey = driver.find_element("css selector", ".g-recaptcha").get_attribute("data-sitekey")
def call(method, payload):
data = requests.post(
f"{API}/{method}", json={"clientKey": KEY, **payload}, timeout=30
).json()
if data.get("errorId"):
raise RuntimeError(data.get("errorCode"))
return data
task_id = call("createTask", {"task": {
"type": "RecaptchaV2TaskProxyless",
"websiteURL": driver.current_url,
"websiteKey": sitekey,
}})["taskId"]
deadline = time.time() + 300
token = None
while time.time() < deadline:
time.sleep(2)
result = call("getTaskResult", {"taskId": task_id})
if result.get("status") == "ready":
token = result["solution"]["gRecaptchaResponse"]
break
if token is None:
raise TimeoutError("the task was not solved in time")
driver.execute_script(
"""
var ta = document.getElementById('g-recaptcha-response');
ta.value = arguments[0];
var submit = document.getElementById('recaptcha-demo-submit');
if (submit) { submit.removeAttribute('disabled'); }
""",
token,
)
driver.find_element("css selector", "#recaptcha-demo-submit").click()
Notice what is missing: no WebDriverWait, no expected_conditions, no retry loop around the textarea. The API poll already did the waiting. The browser only receives the finished token and uses it.
Injection is the one browser step that has to be careful. Set the textarea value directly, then re-enable whatever button the page disabled. Some pages do not use a submit button at all; they call the function named in the widget's data-callback attribute. In that case, call the callback after setting the textarea value, for example window[arguments[0]]() if the callback name is exposed globally. The widget's own JavaScript will then run as if the user solved the challenge in place.
A few details keep this reliable. Poll the task from Python, not from the browser, so the Selenium session stays clean. Store the site key from the page at runtime instead of hardcoding it. If the site binds tokens to the IP address, switch to a proxy task type. Keep the deadline shorter than the token lifetime and submit as soon as ready arrives.
The same pattern works for invisible v2 widgets and for pages that replace the checkbox with a badge. In those cases there is nothing to click and no visible state to watch, so a DOM wait is hopeless; the API task is the only reliable signal. Enterprise and v3 variants work the same way through their own task types, with the token going into the field your application already expects.
When the flow is arranged this way, the test waits for one clear event: the API says ready. Everything else is just moving data into the right field.
When you are ready to stop clicking checkboxes, grab an API key at https://neurocaptcha.com/en/register.
Comments
Join the discussionNo comments yet. Be the first to comment.