DEV Community

Tino K.
Tino K.

Posted on

Why Python `requests` Fails on Cloudflare (and the curl_cffi Fix)

Disclosure: This article contains affiliate links. If you register or purchase through these links, I may earn a small commission at no extra cost to you.

Last month, a client asked me to automate inventory checks across several e-commerce sites. The script was dead simple: requests.Session(), reasonable headers, rotating User-Agent strings, and polite sleep intervals between requests.

It ran fine for about twenty minutes, and then:

HTTPError: 403 Client Error: Forbidden for url: https://target-domain.com/catalog
Enter fullscreen mode Exit fullscreen mode

Changing User-Agents didn't help. Adding Accept-Language, Sec-Ch-Ua, and random referrers did nothing.

The server wasn't blocking the HTTP payload. It was terminating the connection during the TLS handshake before Python even sent the GET line.


What Actually Causes the 403

When you call requests.get(), Python uses the system OpenSSL library. OpenSSL announces cipher suites, TLS extensions, and elliptic curve algorithms in a signature unique to Python.

Anti-bot systems (Cloudflare Turnstile, DataDome, Akamai) calculate a hash of these handshake parameters—commonly known as a JA3 or JA4 fingerprint.

Parameter Standard Python requests Real Google Chrome
TLS Version Order Python/OpenSSL default GREASE + TLS 1.3 / 1.2
Cipher Suites Standard server-side ciphers Chrome-specific prioritized ciphers
HTTP/2 Frames Often defaults to HTTP/1.1 Specific SETTINGS & WINDOW_UPDATE frames
Firewall Verdict Bot (403 Forbidden) Human Visitor (200 OK)

Even if your User-Agent says Mozilla/5.0 (Windows NT 10.0; Win64; x64)..., Cloudflare inspects the TLS layer. If the fingerprint doesn't match the announced browser, you get dropped immediately.


The Fix: curl_cffi

Rather than running heavy, resource-draining headless browsers like Selenium or Playwright just to bypass a handshake check, you can use curl_cffi.

It is a Python wrapper around curl-impersonate that clones Chrome and Safari's network fingerprints byte-for-byte at the socket level.

pip install curl_cffi
Enter fullscreen mode Exit fullscreen mode

Here is the exact drop-in implementation:

from curl_cffi import requests

def scrape(url: str, proxy: str = None):
    # Standard desktop headers
    headers = {
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
        "Accept-Language": "en-US,en;q=0.9",
        "Upgrade-Insecure-Requests": "1",
    }

    proxies = {"http": proxy, "https": proxy} if proxy else None

    try:
        # impersonate="chrome124" matches the exact TLS cipher order,
        # ALPN protocols, and HTTP/2 settings of Chrome desktop
        response = requests.get(
            url,
            headers=headers,
            impersonate="chrome124",
            proxies=proxies,
            timeout=15,
        )

        print(f"[{response.status_code}] {url} - {len(response.content)} bytes")
        return response.text

    except requests.errors.RequestsError as e:
        print(f"Network error on {url}: {e}")
        return None

if __name__ == "__main__":
    # Test on a protected test endpoint
    target = "https://nowsecure.nl"
    content = scrape(target)
    if content and "Checking your browser" not in content:
        print("Bypassed challenge successfully.")
Enter fullscreen mode Exit fullscreen mode

Run this against nowsecure.nl or any basic Cloudflare verification page. You will get a clean 200 OK without triggering a Javascript challenge.


The Next Wall: IP Reputation

Fixing the TLS fingerprint solves the immediate 403 on low-volume tests. But the moment you start requesting 200+ pages, you will hit an IP-level rate limit.

A few practical notes from running crawlers in production:

  1. Free proxy lists are a waste of time: Don't scrape public proxy sites. Over 90% of those IPs are already on Spamhaus or Cloudflare blacklists, and the rest die within 10 minutes.
  2. Datacenter IPs get flagged fast: IPs from AWS (us-east-1), Hetzner, or DigitalOcean have known ASN ranges. Cloudflare flags them with stricter challenge thresholds than home broadband connections.
  3. Use residential pools for scale:
    • For budget testing, I keep a pool on Webshare. They give you 10 permanent proxies on a free tier without requiring a credit card, which is handy for validating a script before spending anything. Their paid residential bandwidth is around the cheapest available if you run high volume.
    • For heavily guarded enterprise targets (like LinkedIn or Amazon), you'll likely need an infrastructure provider like Bright Data, which has deeper proxy pool rotation but costs significantly more.

Summary Checklist Before Deploying

  • Drop requests on protected targets; swap to curl_cffi with impersonate="chrome124".
  • Keep HTTP/2 enabled (supported natively by curl_cffi).
  • Pass headers that match modern Chrome (do not invent weird casing).
  • Route through residential IPs if scraping more than a few dozen pages per session.

Top comments (0)