Solve Cloudflare Turnstile with Selenium in Python
Selenium is still the most common way to automate a browser from Python — and Cloudflare Turnstile is one of the most common reasons a Selenium script stops working. The widget detects WebDriver-controlled browsers and refuses to complete, so your script waits on a spinner that never turns into a check mark.
Instead of fighting the detection, you can have SolverCF solve the Turnstile challenge and hand the resulting token to the page from Selenium. Here is the complete workflow.
Only automate sites you own or have permission to test, and follow each site's terms of service.
Requirements
pip install selenium requests
Selenium 4.6+ downloads the matching ChromeDriver automatically. You also need a SolverCF client key from the dashboard; new accounts start with 100 free solves.
Step 1: Open the page and read the site key
import re
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
URL = "https://example.com/login"
driver = webdriver.Chrome()
driver.get(URL)
WebDriverWait(driver, 15).until(EC.presence_of_element_located(
(By.CSS_SELECTOR, '[data-sitekey], iframe[src*="challenges.cloudflare.com"]')))
def get_site_key(driver) -> str:
elements = driver.find_elements(By.CSS_SELECTOR, "[data-sitekey]")
if elements:
return elements[0].get_attribute("data-sitekey")
frame = driver.find_element(By.CSS_SELECTOR, 'iframe[src*="challenges.cloudflare.com"]')
match = re.search(r"/(0x4[\w-]+)/", frame.get_attribute("src"))
if not match:
raise ValueError("Turnstile site key not found")
return match.group(1)
site_key = get_site_key(driver)
user_agent = driver.execute_script("return navigator.userAgent")
We also read the browser's own User-Agent so we can ask the solver to use the same one.
Step 2: Solve Turnstile with the API
import time
import requests
API = "https://solvercf.com/token/extension"
CLIENT_KEY = "YOUR_CLIENT_KEY"
def solve_turnstile(website_url: str, website_key: str, user_agent: str = None, timeout: int = 90) -> dict:
task = {"type": "TurnstileTask", "websiteUrl": website_url, "websiteKey": website_key}
if user_agent:
task["userAgent"] = user_agent
created = requests.post(f"{API}/createTask", json={"clientKey": CLIENT_KEY, "task": task}, timeout=30).json()
if created.get("errorId") != 0:
raise RuntimeError(created.get("errorDescription"))
deadline = time.time() + timeout
while time.time() < deadline:
time.sleep(1.5)
result = requests.post(f"{API}/getTaskResult",
json={"clientKey": CLIENT_KEY, "taskId": created["taskId"]}, timeout=30).json()
if result.get("errorId") != 0:
raise RuntimeError(result.get("errorDescription"))
if result["status"] == "ready":
return result["solution"]
if result["status"] in ("failed", "expired"):
raise RuntimeError(f"task {result['status']}")
raise TimeoutError("Turnstile not solved in time")
solution = solve_turnstile(URL, site_key, user_agent)
Passing userAgent keeps the token consistent with the browser that will submit it. Headless Chrome reports HeadlessChrome in its User-Agent — set a normal one with --user-agent=... in your Chrome options before you start.
Step 3: Inject the token into the page
Turnstile normally stores its token in a hidden cf-turnstile-response input and calls an optional callback. Reproduce both with JavaScript:
INJECT = """
const token = arguments[0];
let inputs = document.querySelectorAll('[name="cf-turnstile-response"]');
if (inputs.length === 0) {
const input = document.createElement('input');
input.type = 'hidden';
input.name = 'cf-turnstile-response';
document.querySelector('form')?.appendChild(input);
inputs = [input];
}
inputs.forEach(i => { i.value = token; });
const cb = document.querySelector('[data-callback]')?.getAttribute('data-callback');
if (cb && typeof window[cb] === 'function') window[cb](token);
"""
driver.execute_script(INJECT, solution["token"])
Step 4: Submit the form
driver.find_element(By.NAME, "email").send_keys("[email protected]")
driver.find_element(By.NAME, "password").send_keys("your-password")
driver.find_element(By.CSS_SELECTOR, 'button[type="submit"]').click()
WebDriverWait(driver, 20).until(EC.url_changes(URL))
print("Now at:", driver.current_url)
driver.quit()
Change the selectors to match your target form.
Troubleshooting
The form still says "verification failed". The token was probably stale or used twice. Solve immediately before submitting and never reuse a token.
The submit button stays disabled.
The site enables it from the Turnstile callback. Make sure the data-callback function is being called — if the site registered the callback through turnstile.render() instead, find the function name in the page scripts and call it with the token.
You see a full-page "Just a moment..." screen.
That is a Cloudflare Challenge rather than a widget. Solve it for a cf_clearance cookie (cloudflareTaskType: "cookie", see the cf_clearance guide), then add it with driver.add_cookie() while using the same proxy and User-Agent.
Is undetected-chromedriver enough on its own? Sometimes, but Cloudflare updates its detection regularly and a stealth browser that works today can fail tomorrow. Combining your browser with an external solver removes that dependency.
Learn more
- Full parameter reference: Cloudflare Turnstile docs
- No browser needed? Bypass Turnstile with Python requests
- Using Node.js: Solve Turnstile in Playwright