Cloudflare
How to get past the Cloudflare challenge page in Python
The Cloudflare challenge page guards an entire site, not just a form. Passing it gives a browser a cf_clearance cookie, and that cookie only works from the same IP and with the same user agent.
What you are dealing with
When Cloudflare decides a request needs checking, it answers with an interstitial instead of the page: the "Just a moment..." or "Verifying you are human" screen, today usually a managed challenge. A real browser runs the challenge script, sometimes shows an interactive check, and on success receives a cookie called cf_clearance. Subsequent requests that carry the cookie are let through for a period the site owner configures.
A Python HTTP client cannot run that script. What it can do is obtain the cookie from a solving task and send it along. The catch is that Cloudflare binds the clearance to the visitor: the IP address it was issued to and the user agent that earned it. That is why the AntiCloudflareTask requires your proxy, and why your script must then use the same proxy and the user agent returned in the solution.
Requirements
- A proxy you control in the form
http://user:pass@host:portthat keeps the same exit IP for the whole session. A rotating proxy that changes IP per request will invalidate the cookie on the next call; use a sticky session. - Python 3.10+ with
requests. - The URL where the challenge appears.
Detect the challenge before solving
Do not solve on every request. Detect the challenge, solve once, and reuse the cookie until it stops working. Cloudflare marks challenge responses with a cf-mitigated: challenge header, and the HTML has a recognisable title.
def is_cf_challenge(resp) -> bool:
if resp.headers.get("cf-mitigated", "").lower() == "challenge":
return True
looks_blocked = resp.status_code in (403, 503) and "cloudflare" in resp.headers.get("server", "").lower()
return looks_blocked and ("Just a moment" in resp.text or "challenge-platform" in resp.text)
Checking the server header avoids false alarms from an ordinary 403 served by the origin. A 403 from Cloudflare without any challenge markers is usually a firewall block, which no token or cookie changes; the article on error 1020 explains that case.
Request the clearance
import time
import requests
SOLVER = "https://gatesolver.com"
MY_KEY = "YOUR_API_KEY"
def fetch_clearance(page_url: str, proxy_url: str) -> dict:
job = requests.post(f"{SOLVER}/createTask", timeout=30, json={
"clientKey": MY_KEY,
"task": {"type": "AntiCloudflareTask", "websiteURL": page_url, "proxy": proxy_url},
}).json()
if job.get("errorId"):
raise RuntimeError(f"createTask refused: {job.get('errorCode')} {job.get('errorDescription', '')}")
started = time.monotonic()
while time.monotonic() - started < 125:
time.sleep(3)
state = requests.post(f"{SOLVER}/getTaskResult", timeout=30,
json={"clientKey": MY_KEY, "taskId": job["taskId"]}).json()
if state.get("errorId"):
raise RuntimeError(f"getTaskResult: {state.get('errorCode')}")
phase = state["status"]
if phase == "ready":
return state["solution"] # cookies, token, userAgent
if phase == "failed":
break
raise RuntimeError("clearance task ended without a cookie (not charged)")
The solution holds a cookies object with cf_clearance (and sometimes other Cloudflare cookies), a token with the same clearance value, and the userAgent the challenge was passed with. You can also send your own userAgent in the task when your client must present a specific browser string; then use exactly that one afterwards.
Build a session that keeps the clearance
from urllib.parse import urlsplit
def cleared_session(page_url: str, proxy_url: str) -> requests.Session:
sol = fetch_clearance(page_url, proxy_url)
host = urlsplit(page_url).hostname
sess = requests.Session()
sess.proxies.update({"http": proxy_url, "https": proxy_url})
sess.headers.update({
"User-Agent": sol["userAgent"],
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.9",
})
for name, value in sol.get("cookies", {}).items():
sess.cookies.set(name, value, domain=host, path="/")
return sess
sticky_proxy = "http://user:pass@203.0.113.10:8080" # keeps one exit IP
target = "https://catalog.example.com/products?page=1"
s = cleared_session(target, sticky_proxy)
r = s.get(target, timeout=30)
print(r.status_code, is_cf_challenge(r))
Every request from this session goes through the same proxy, carries the same user agent and sends the cookie. Setting the cookie for the exact hostname matters: a clearance issued on catalog.example.com is scoped by Cloudflare to that site's domain, and requests to a different subdomain behind a different zone may need their own solve.
Keep it working over time
The cookie expires after the period the site owner has set, and Cloudflare may challenge again if traffic patterns change. Wrap your fetches: if is_cf_challenge() returns true, build a new cleared session and repeat the request once. If the challenge returns immediately after a fresh solve, slow down; that usually means the request rate from that IP looks abnormal to the site. The guide on reusing cf_clearance covers session design in more depth.
When the cookie is right but the challenge persists
Cloudflare can look at more than the cookie. Bot management also considers the TLS and HTTP/2 characteristics of the client, and the defaults of Python's requests (built on OpenSSL through urllib3) do not resemble any browser. If you send the correct cookie, proxy and user agent and still get challenged on every request, the client fingerprint is the likely cause. Options include an HTTP client that reproduces a browser's TLS handshake, such as the curl_cffi package with its impersonation setting (check its current documentation for the supported browser versions), or running the requests through a real browser with Playwright. The glossary entry on TLS fingerprinting explains the mechanism.
Scaling across many pages
One clearance covers every page of the same site from the same IP, so crawl structure matters more than solve speed. Keep one cleared session per proxy IP and give each session its own queue of URLs, rather than spreading every URL across all IPs. That way each cookie is reused as much as possible and each IP sends a steady, moderate stream of requests. When you need more throughput, add IPs and sessions instead of raising the rate on one, which tends to bring the challenge back. Store each session's cookie, user agent and proxy together, so a worker restart can resume with a clearance that is still valid instead of solving again.
Errors and costs
- ERROR_INVALID_TASK_DATA with "proxy" in the description: the proxy field is missing or malformed. It is required for this task.
- ERROR_CAPTCHA_UNSOLVABLE: often a proxy that is slow, blocked or unreachable from our side. Test the proxy, then retry; failed tasks are free.
- Clearance works once, then fails: your proxy rotated. Use a sticky session.
A solved challenge costs $0.84 per 1,000 tasks, charged when the cookie is delivered. Because one cookie covers many requests, the cost per page is usually a small fraction of that. Use it for work you are allowed to do: public catalog monitoring, testing your own Cloudflare configuration, accessibility checks. Field details are on the Cloudflare Challenge task page.
Common questions
Why does AntiCloudflareTask need my proxy?
Cloudflare binds cf_clearance to the IP that passed the challenge. The task passes it from your proxy so the cookie works on your requests.
Can I use a rotating proxy?
Only with a sticky session that keeps one exit IP. If the IP changes, the cookie stops working.
Which user agent should my script send?
The userAgent returned in the solution, or the one you sent in the task. It must match the one used to pass the challenge.
How long does cf_clearance last?
The site owner sets it in Cloudflare. Detect the challenge again and solve a new cookie when it reappears.
Can this get past a firewall block such as error 1020?
No. A block is a rule set by the site owner, not a challenge, and no cookie changes it.
Keep reading
- Cloudflare Challenge solver$0.84 per 1,000 tasks, answers under 10 seconds.
- cf_clearance cookieThe cookie Cloudflare sets after a passed challenge, why it only works from one IP and user agent, and its lifespan.
- Reusing cf_clearance cookies safelyDesign sessions around cf_clearance: bind each cookie to one IP and user agent, track its age and refresh only when needed.
- TLS fingerprintingThe ClientHello message reveals which library opened the connection, which is why Python requests never looks like Chrome.