Cloudflare
How to solve Cloudflare Turnstile in Python
Turnstile is Cloudflare's widget for forms, and its answer is a single token in a field called cf-turnstile-response. This guide gets that token from Python with an async client, so many forms can be handled at once.
Turnstile in one minute
Cloudflare Turnstile is a widget site owners embed in their own forms, much like a checkbox CAPTCHA. Most visitors never click anything: the widget runs a few browser checks and, when satisfied, writes a token into a hidden input. The site's back end sends that token to Cloudflare's siteverify endpoint before it accepts the login, signup or comment.
Turnstile is not the same thing as Cloudflare's full screen "Just a moment" check. That one protects whole pages, returns a clearance cookie, and needs a different task. If you are not sure which you face, the guide on how to tell Cloudflare protections apart settles it quickly. This guide is about the widget inside a form.
Collect the parameters
A Turnstile task needs the page URL and the site key. The key sits in the data-sitekey attribute of the element with class cf-turnstile and always starts with 0x4. Two optional values matter on some sites:
- action: a label the site attaches to the widget (
data-action), such aslogin. Cloudflare returns it during verification so the site can check it. - cData: free form customer data (
data-cdata), often a session or request id that the back end compares.
If the site sets either value, send it in the task's metadata object. When the widget is created from JavaScript with turnstile.render(), the same values sit in the options object; the guide on how to find Turnstile parameters shows where to look.
Why async for Turnstile
Forms protected by Turnstile often come in batches: a set of partner portals to check, a list of public search forms, a QA suite that submits many variations. An async client lets one Python process keep many tasks in flight while it waits, without threads. The API places no limit on concurrent tasks, and polling every three seconds keeps the number of requests modest. Install the library with pip install aiohttp.
The async client
import asyncio
import aiohttp
GATE_URL = "https://gatesolver.com"
class TurnstileFailed(RuntimeError):
pass
async def gate_json(http: aiohttp.ClientSession, method: str, body: dict) -> dict:
async with http.post(f"{GATE_URL}/{method}", json=body) as resp:
payload = await resp.json(content_type=None)
if payload.get("errorId"):
raise TurnstileFailed(f'{payload.get("errorCode")} {payload.get("errorDescription", "")}'.strip())
return payload
async def turnstile_token(http, api_key, url, sitekey, action=None, cdata=None) -> dict:
task = {"type": "AntiTurnstileTaskProxyLess", "websiteURL": url, "websiteKey": sitekey}
extra = dict(pair for pair in (("action", action), ("cdata", cdata)) if pair[1])
if extra:
task["metadata"] = extra
created = await gate_json(http, "createTask", {"clientKey": api_key, "task": task})
for attempt in range(41):
await asyncio.sleep(3)
poll_reply = await gate_json(http, "getTaskResult", {"clientKey": api_key, "taskId": created["taskId"]})
if poll_reply["status"] == "ready":
return poll_reply["solution"] # {"token": ..., "userAgent": ...}
if poll_reply["status"] == "failed":
raise TurnstileFailed("task failed; not billed")
raise TurnstileFailed("no Turnstile token after about two minutes")
The function returns the whole solution, not just the token, because the userAgent next to it is useful when you post the form. content_type=None tells aiohttp to parse JSON even if a proxy in between changes the response header. The metadata dictionary is built only from the values you actually have, so the task never carries empty strings.
Post the form with the token
On a classic form, the token travels as the field cf-turnstile-response. Load the page, collect the hidden inputs, solve, and submit with one session so cookies carry over.
import re
async def submit_contact(api_key: str):
page = "https://help.example.org/contact"
timeout = aiohttp.ClientTimeout(total=60)
async with aiohttp.ClientSession(timeout=timeout) as gate, aiohttp.ClientSession(timeout=timeout) as site:
html = await (await site.get(page)).text()
sitekey = re.search(r'class="cf-turnstile"[^>]*data-sitekey="(0x4[\w-]+)"', html).group(1)
solved = await turnstile_token(gate, api_key, page, sitekey, action="contact")
form = {"name": "QA run", "email": "qa@example.org", "cf-turnstile-response": solved["token"]}
async with site.post(page, data=form, headers={"User-Agent": solved["userAgent"]}) as r:
print(r.status, r.url)
asyncio.run(submit_contact("YOUR_API_KEY"))
Two sessions keep concerns apart: gate only talks to the solver, site holds the target's cookies. The regular expression assumes class comes before data-sitekey; for anything less predictable, parse with Beautiful Soup and select .cf-turnstile[data-sitekey]. Add the CSRF field and any other hidden inputs you see when you submit the form by hand.
Confirm that the submit worked
A 200 status alone proves little, because many forms answer 200 with the same page and an error message when verification fails. Decide on a success signal before you automate: a redirect to a thank you URL, a specific phrase in the response, or a JSON field such as "ok": true from the site's API. Check for it explicitly and log the task id next to the outcome. When a run of submits starts failing while the API keeps returning tokens, that log tells you immediately whether timing, missing metadata or a site change is to blame.
Solving a batch
The real payoff of async is a list of forms. Wrap each job in a coroutine and run them with asyncio.gather, guarded by an asyncio.Semaphore so you decide how many run at once:
async def run_batch(jobs, api_key, parallel=10):
gate_slots = asyncio.Semaphore(parallel)
async with aiohttp.ClientSession() as gate:
async def one(job):
async with gate_slots:
return await turnstile_token(gate, api_key, job["url"], job["sitekey"], job.get("action"))
return await asyncio.gather(*(one(j) for j in jobs), return_exceptions=True)
With return_exceptions=True a single failed task does not cancel the others; inspect each result and retry the ones that raised. Ten parallel jobs polling every three seconds make roughly 200 status calls a minute, well under the 600 per minute allowed per key.
Handling errors
- ERROR_INVALID_TASK_DATA: the description names the field. Usually an empty site key because the regex did not match.
- ERROR_CAPTCHA_UNSOLVABLE and ERROR_SERVICE_UNAVAILABLE: free; create a new task after a short pause.
- ERROR_ZERO_BALANCE: stop the batch and top up rather than letting every job fail.
- ERROR_RATE_LIMIT: too many calls per minute; lower the semaphore or poll a bit less often.
When the site refuses the token
Turnstile tokens are short lived (Cloudflare documents a lifetime of 300 seconds) and valid for one verification. Submit soon after solving and never reuse a token for a retry. If the site checks action or cData during verification, a token produced without them can be refused, so pass both whenever the widget declares them. Pages that read the token through a JavaScript callback rather than the form field need a browser; the Node.js and Playwright guide covers that path.
A Turnstile task costs $0.84 per 1,000 solved and usually returns under 3 seconds. The Turnstile task page lists every field, including the alternative type names that older clients send.
Common questions
Does this need a browser?
Not for forms that post cf-turnstile-response as a normal field. Sites that read the token in a JavaScript callback are easier with a browser.
What are action and cData?
Optional values the site attaches to the widget. Cloudflare returns them on verification, so send them in metadata when the page sets them.
How do I tell a Turnstile key from a reCAPTCHA key?
Turnstile site keys start with 0x4; reCAPTCHA keys usually start with 6L.
Can I use requests instead of aiohttp?
Yes. The API calls are the same; aiohttp only makes it easy to wait on many tasks in one process.
How long is a Turnstile token valid?
Cloudflare documents 300 seconds, and each token verifies once. Solve close to the submit.
Keep reading
- Cloudflare Turnstile solver$0.84 per 1,000 tasks, answers under 3 seconds.
- Find Turnstile site key, action and cDataWhere Turnstile keeps its site key, action and cData: widget attributes, turnstile.render options and explicit rendering setups.
- Cloudflare TurnstileThe Turnstile widget from Cloudflare, its managed, non-interactive and invisible modes, and the cf-turnstile-response token field.
- Tell Turnstile, managed challenges and blocks apartStatus codes, headers, page markers and cookies that separate a Turnstile widget, a challenge page and a hard Cloudflare block.