How to Get the cf_clearance Cookie and Scrape Cloudflare Sites with Python
If your scraper receives a page titled "Just a moment..." (or an HTTP 403 with Cloudflare branding) instead of the content you asked for, the site is protected by a Cloudflare Challenge. A real browser passes it in a few seconds and receives a cookie called cf_clearance. Every later request that carries that cookie is let straight through.
So the goal is simple: get a valid cf_clearance cookie, then reuse it from Python. This guide shows how to do that with the SolverCF API and requests, and — just as important — the rules that make the cookie actually work.
Only scrape sites you are allowed to, keep request rates reasonable, and follow each site's terms of service.
Why cf_clearance is tied to you
Cloudflare binds the cookie to the environment that solved the challenge:
- IP address — the cookie only works from the IP that solved it.
- User-Agent and Client Hints —
User-Agent,Sec-CH-UA,Sec-CH-UA-MobileandSec-CH-UA-Platformmust match.
That is why you must give the solver the same proxy your scraper will use, and then copy the solver's headers into your scraper. Skip either step and Cloudflare answers with 403 again.
Step 1: Read the challenge parameters
Open the challenge page source. Cloudflare embeds its options in a script:
<script>
window._cf_chl_opt = {
cType: 'interactive',
sitekey: '0x4AAAAAAAAjq6WYeRDKmebM',
cData: 'a35dc237aee2b54e',
chlPageData: 'iT10BhAtiTDkBgg6...'
};
</script>
| Page value | API parameter |
|---|---|
sitekey |
websiteKey |
cType |
pageAction (usually interactive) |
cData |
data |
chlPageData |
pageData |
A small helper extracts them from the HTML Cloudflare returned:
import re
def challenge_params(html: str) -> dict:
def pick(name):
m = re.search(rf"{name}\s*:\s*'([^']*)'", html)
return m.group(1) if m else None
params = {
"websiteKey": pick("sitekey"),
"pageAction": pick("cType") or "interactive",
"data": pick("cData"),
"pageData": pick("chlPageData"),
}
return {k: v for k, v in params.items() if v}
Step 2: Solve the challenge through your proxy
Create a TurnstileTask with cloudflareTaskType: "cookie" and pass your proxy. Supported proxy formats include host:port, host:port:user:pass, user:pass@host:port, and http://, socks5:// URLs.
import time
import requests
API = "https://solvercf.com/token/extension"
CLIENT_KEY = "YOUR_CLIENT_KEY"
PROXY = "203.0.113.10:8080:user:pass" # the proxy your scraper will use
def get_clearance(url: str, params: dict, timeout: int = 120) -> dict:
created = requests.post(f"{API}/createTask", json={
"clientKey": CLIENT_KEY,
"task": {
"type": "TurnstileTask",
"websiteUrl": url,
"cloudflareTaskType": "cookie",
"proxy": PROXY,
**params,
},
}, 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("challenge not solved in time")
The solution contains everything your scraper needs:
{
"cookie": "cf_clearance=E4r8...; path=/; domain=.example.com; Secure; HttpOnly",
"userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) ... Chrome/124.0.0.0 Safari/537.36",
"secChUa": "\"Chromium\";v=\"124\", \"Google Chrome\";v=\"124\", \"Not-A.Brand\";v=\"99\"",
"secChUaMobile": "?0",
"secChUaPlatform": "\"Windows\""
}
Step 3: Reuse the cookie with requests
Build a session that sends the cookie, the solver's headers, and the same proxy:
def proxy_url(proxy: str) -> str:
# "host:port:user:pass" -> "http://user:pass@host:port"
parts = proxy.split(":")
if len(parts) == 4:
host, port, user, password = parts
return f"http://{user}:{password}@{host}:{port}"
return proxy if "://" in proxy else f"http://{proxy}"
def cloudflare_session(solution: dict) -> requests.Session:
s = requests.Session()
s.proxies = {"http": proxy_url(PROXY), "https": proxy_url(PROXY)}
s.headers.update({
"User-Agent": solution["userAgent"],
"Sec-CH-UA": solution["secChUa"],
"Sec-CH-UA-Mobile": solution["secChUaMobile"],
"Sec-CH-UA-Platform": solution["secChUaPlatform"],
"Accept-Language": "en-US,en;q=0.9",
})
name, value = solution["cookie"].split(";")[0].split("=", 1)
s.cookies.set(name, value)
return s
TARGET = "https://example.com/products"
first = requests.get(TARGET, proxies={"https": proxy_url(PROXY)}, timeout=30)
if "Just a moment" in first.text:
solution = get_clearance(TARGET, challenge_params(first.text))
session = cloudflare_session(solution)
page = session.get(TARGET, timeout=30)
print(page.status_code, len(page.text))
From here, keep using the same session for every request to that site.
Keeping the cookie alive
- Reuse it. A
cf_clearancecookie usually stays valid for a while — often 30 minutes or more, depending on the site's settings. Solve once and scrape many pages instead of solving per request. - Refresh on 403. When a response turns back into a challenge page or a 403, solve again and replace the cookie.
- One cookie per proxy. If you rotate proxies, keep a separate clearance (and session) for each IP.
- Don't change the User-Agent mid-session. A different browser fingerprint invalidates the clearance.
Troubleshooting
| Symptom | Likely cause |
|---|---|
| 403 right after solving | Request sent from a different IP than the proxy you passed |
| Works once, then 403 | User-Agent or Client Hints differ between requests |
| Task fails repeatedly | Proxy is dead, slow, or already flagged — try a clean residential proxy |
| Error 1020 "Access denied" | A firewall rule blocks you outright — see Cloudflare 403 causes and fixes |
Summary
cf_clearance is the key that opens a Cloudflare-protected site, but it only fits the lock it was cut for: the same IP, the same User-Agent and the same Client Hints. Solve through the proxy you scrape with, copy the solver's headers, reuse the cookie, and refresh it when it expires.
The full parameter list is in the Cloudflare Challenge documentation. If the protected page shows a Turnstile widget inside a form rather than a full-page challenge, use the Turnstile token guide instead.