Skip to content
Guide

Scrapy Cloudflare 403: Why Your Spider Gets Blocked and How to Fix It

NSLSolver TeamPublished Updated 9 min read

Scrapy gets 403 from Cloudflare for one of four reasons: its default User-Agent announces a bot, its TLS handshake does not look like a browser, the IP has a poor reputation, or Cloudflare served a JavaScript challenge that Scrapy cannot run. The first three are fixable inside Scrapy (headers, scrapy-impersonate, better proxies). The fourth needs a cf_clearance cookie from something that executes the challenge, replayed with the same User-Agent and IP.

Below: what each log line means, a spider that tells you which case you are in, the fixes in order of cost, and a downloader middleware that plugs a cf_clearance cookie into an existing project. Scrapy behaviour is quoted from the 2.20.0 source and docs, plugin details from their READMEs, all checked 2026-12-01.

Quick answer: what your Scrapy log means

The same 403 can mean very different things. Match the symptom, then jump to the fix.

DEBUG: Crawled (403) <GET https://target-site.com/> (referer: None)
Cloudflare (or the site) refused the request. Look at the body and headers before changing anything (step 1).
INFO: Ignoring response <403 https://target-site.com/>: HTTP status code is not handled or not allowed
HttpErrorMiddleware dropped the 403 before your callback ran. Add handle_httpstatus_list = [403] (or HTTPERROR_ALLOWED_CODES) while you debug.
403 + <title>Just a moment...</title> / cf-mitigated: challenge
A JavaScript challenge. Scrapy cannot run it. Use a browser (scrapy-playwright) or replay a cf_clearance cookie (step 5).
403 "Sorry, you have been blocked" / Error 1020
A firewall rule, nothing to solve. Change IP or region, or ask the site owner.
Works in requests or the browser, 403 in Scrapy
Default UA "Scrapy/2.20.0 (+https://scrapy.org)" or a non-browser TLS handshake. Set a browser USER_AGENT, then try scrapy-impersonate for a browser TLS fingerprint.
429 or Error 1015 after a few hundred pages
Rate limiting. Lower concurrency, add DOWNLOAD_DELAY or AutoThrottle, spread over IPs.
TypeError: download_request() takes 2 positional arguments but 3 were given
An old scrapy-impersonate with a newer Scrapy (issue #55). Upgrade scrapy-impersonate (1.11.0 is current).
scrapy-playwright crawl hangs after N pages
Pages opened with playwright_include_page were never closed. Close the page in the callback and in an errback; open pages count toward PLAYWRIGHT_MAX_PAGES_PER_CONTEXT.

Log formats are quoted from Scrapy 2.20.0 (logformatter.py, httperror.py, default_settings.py); plugin behaviour from the scrapy-impersonate README and scrapy-playwright docs, checked 2026-12-01.

scrapy-impersonate runs on curl_cffi. For its fingerprint targets and why impersonation alone cannot pass a challenge, see curl_cffi Cloudflare 403 →

Why Scrapy gets 403 on Cloudflare sites

Cloudflare decides in layers, and stock Scrapy fails the first ones before content is even considered. Its default USER_AGENT is "Scrapy/<version> (+https://scrapy.org)", which any bot rule can match. Its downloader is Twisted with OpenSSL, not a browser network stack. Scrapy's docs do not describe its TLS fingerprint, but users in Scrapy issue #4951 ("Identical requests sent by Scrapy vs Requests module returning different status codes") report Cloudflare 403s that disappear with another client, and a maintainer notes that other clients behave differently "during TLS negotiation" and in header casing.

Behind that sit IP reputation (datacenter ranges are challenged far more often) and the JavaScript challenge itself. Scrapy has no JavaScript engine, so a challenge page is a dead end for any setting. Note also that Scrapy never retries a 403 by default: the default RETRY_HTTP_CODES are [408, 429, 500, 502, 503, 504, 522, 524].

Step 1: let the 403 through and read it

HttpErrorMiddleware drops non-2xx responses and logs "Ignoring response <403 ...>: HTTP status code is not handled or not allowed", so your callback never sees the block page. While debugging, allow it with the handle_httpstatus_list spider attribute (or the HTTPERROR_ALLOWED_CODES setting). Scrapy's docs warn that handling non-200 responses is usually a bad idea in production, so remove it once you know the cause. Cloudflare marks challenge pages with the cf-mitigated: challenge response header, which is more reliable than parsing HTML.

diagnose_spider.py
import scrapy


class DiagnoseSpider(scrapy.Spider):
    name = "diagnose"
    start_urls = ["https://target-site.com/"]
    # Let blocked responses reach parse() instead of "Ignoring response <403 ...>"
    handle_httpstatus_list = [403, 429, 503]

    def parse(self, response):
        mitigated = response.headers.get("cf-mitigated", b"").decode()
        title = response.css("title::text").get(default="")
        self.logger.info(
            "status=%s cf-mitigated=%r cf-ray=%r title=%r",
            response.status, mitigated,
            response.headers.get("cf-ray", b"").decode(), title,
        )
        if mitigated == "challenge" or "Just a moment" in title:
            self.logger.warning("JS challenge: no header or TLS tweak passes it, you need cf_clearance")
        elif b"1020" in response.body or b"you have been blocked" in response.body:
            self.logger.warning("Firewall rule (1020): nothing to solve, change IP or ask the site owner")
        elif response.status == 429 or b"1015" in response.body:
            self.logger.warning("Rate limited: slow down")
        else:
            self.logger.warning("No challenge marker: check User-Agent, TLS fingerprint and IP")

Step 2: fix the User-Agent, headers and pace

This is free and sometimes enough on sites with light rules. Send a current browser User-Agent and the Accept headers a browser sends, and slow down. If you still get 403 with no challenge marker, the TLS fingerprint or the IP is the problem, which headers cannot fix.

settings.py
# settings.py: the cheap fixes first
# Scrapy's default UA is "Scrapy/2.20.0 (+https://scrapy.org)", an easy block.
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/<version> Safari/537.36"
DEFAULT_REQUEST_HEADERS = {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "Accept-Language": "en-US,en;q=0.9",
}

# Look less like a burst of bots
CONCURRENT_REQUESTS_PER_DOMAIN = 2
DOWNLOAD_DELAY = 1.0
AUTOTHROTTLE_ENABLED = True

# 403 is NOT in the default RETRY_HTTP_CODES [408, 429, 500, 502, 503, 504, 522, 524].
# Do not add it blindly: retrying a challenge from the same IP just repeats the block.

Step 3: a browser TLS fingerprint with scrapy-impersonate

scrapy-impersonate (github.com/jxlil/scrapy-impersonate, MIT, 1.11.0 released 2026-11-17) is a Scrapy download handler built on curl_cffi, "so it can impersonate browsers' TLS signatures or JA3 fingerprints". You swap the http and https handlers and set the impersonate meta key per request. Setting USER_AGENT = "" lets curl_cffi send the User-Agent that matches the impersonated browser, so the headers and the handshake agree.

Two details from its README matter for Cloudflare. allow_redirects is forced off so Scrapy's redirect and offsite middlewares keep working (re-enabling it bypasses them). Connections are reused per host, impersonate target and proxy, and TLS sessions are never resumed, so requests sent through different proxies cannot be linked that way. Proxies go in the usual meta["proxy"]. Like curl_cffi, it fixes fingerprints, not JavaScript challenges.

impersonate_settings.py
# pip install scrapy-impersonate
# settings.py
DOWNLOAD_HANDLERS = {
    "http": "scrapy_impersonate.ImpersonateDownloadHandler",
    "https": "scrapy_impersonate.ImpersonateDownloadHandler",
}
USER_AGENT = ""   # let curl_cffi send the UA that matches the impersonated browser
TWISTED_REACTOR = "twisted.internet.asyncioreactor.AsyncioSelectorReactor"  # Scrapy's default anyway

# spider.py
import scrapy


class ShopSpider(scrapy.Spider):
    name = "shop"

    def start_requests(self):
        yield scrapy.Request(
            "https://target-site.com/",
            meta={
                "impersonate": "chrome",            # newest Chrome profile of your curl_cffi
                "proxy": "http://user:pass@host:port",
            },
        )

    def parse(self, response):
        self.logger.info("%s %s", response.status, response.headers.get("cf-mitigated"))

Step 4: a real browser with scrapy-playwright

When the response carries cf-mitigated: challenge, something has to run JavaScript. scrapy-playwright (0.0.48, released 2026-07-10, Python 3.10+) routes requests with meta={"playwright": True} through Playwright. Set USER_AGENT = None so Scrapy does not overwrite the browser's own UA; the docs warn that a mismatched UA can make sites "react in unexpected ways". Wait for the challenge to clear before reading the page, and always close pages you asked for with playwright_include_page.

It is not a guaranteed pass. Issue #203 is titled "same settings: scrapy-playwright triggers cloudflare challenge while playwright alone does not", and stock Playwright is detectable. It also costs a browser per concurrent page. A common pattern is to use the browser only to earn cf_clearance, then fetch with scrapy-impersonate.

playwright_spider.py
# pip install scrapy-playwright && playwright install chromium
# settings.py
DOWNLOAD_HANDLERS = {
    "http": "scrapy_playwright.handler.ScrapyPlaywrightDownloadHandler",
    "https": "scrapy_playwright.handler.ScrapyPlaywrightDownloadHandler",
}
TWISTED_REACTOR = "twisted.internet.asyncioreactor.AsyncioSelectorReactor"
USER_AGENT = None   # keep the browser's own UA instead of Scrapy's

# spider.py
import scrapy
from scrapy_playwright.page import PageMethod


class PwSpider(scrapy.Spider):
    name = "pw"

    def start_requests(self):
        yield scrapy.Request(
            "https://target-site.com/",
            meta={
                "playwright": True,
                "playwright_include_page": True,
                "playwright_page_methods": [PageMethod("wait_for_timeout", 8000)],
            },
            errback=self.close_page,
        )

    async def parse(self, response):
        page = response.meta["playwright_page"]
        cookies = await page.context.cookies()
        await page.close()                         # unclosed pages freeze the crawl
        self.logger.info("cf_clearance: %s", any(c["name"] == "cf_clearance" for c in cookies))

    async def close_page(self, failure):
        page = failure.request.meta.get("playwright_page")
        if page:
            await page.close()

Old Cloudflare middlewares to avoid

  • scrapy-cloudflare-middleware: a single release, 0.0.1 from February 2018, built on cfscrape. It targets the old "Checking your browser" page and its setup.py imports pip internals that modern pip no longer has.
  • cfscrape (cloudflare-scrape): last release 2.1.1 in February 2020, documented for Python 2.6 to 3.7, and it needs Node.js. Unmaintained.
  • Packages that wrap cloudscraper inherit its limits on current challenges; see Cloudscraper not working in 2026.
  • Newer options exist: scrapy-zyte-api (0.37.0, November 2026) for Zyte's paid API, and scrapy-camoufox (0.0.12, January 2025, little activity since).

Step 5: replay cf_clearance from a downloader middleware

The cheapest stable setup for a large crawl is: earn cf_clearance once per proxy, then let Scrapy do the fetching. The cookie is bound to the client that earned it, so three things must match on every request: the exact User-Agent, the egress IP and a TLS fingerprint from the same browser family. The cf_clearance cookie guide explains why.

The middleware below gets the cookie from NSLSolver's challenge type, which runs server-side with no browser on your machines. The clearance is issued for an iPhone Safari browser, so it pairs the returned user_agent with scrapy-impersonate's safari_ios target and the same sticky proxy. It sits at priority 650, before Scrapy's CookiesMiddleware (700), and solves again once if the cookie expires.

middlewares.py
# middlewares.py: fetch cf_clearance once, replay it on every request
import requests


class NSLClearanceMiddleware:
    def __init__(self, api_key, proxy, site_key):
        self.api_key, self.proxy, self.site_key = api_key, proxy, site_key
        self.clearance = None   # {"cookies": {...}, "user_agent": "..."}

    @classmethod
    def from_crawler(cls, crawler):
        s = crawler.settings
        return cls(s["NSLSOLVER_API_KEY"], s["NSL_PROXY"], s["CF_SITE_KEY"])

    def _solve(self, url):
        # Blocking call: fine for small crawls, move it to a thread for large ones
        r = requests.post(
            "https://api.nslsolver.com/solve",
            headers={"X-API-Key": self.api_key},
            json={"type": "challenge", "url": url, "site_key": self.site_key, "proxy": self.proxy},
            timeout=120,
        )
        r.raise_for_status()
        data = r.json()
        self.clearance = {"cookies": data["cookies"], "user_agent": data["user_agent"]}

    def process_request(self, request, spider):
        if self.clearance is None:
            self._solve(request.url)
        request.meta["proxy"] = self.proxy                   # SAME proxy as the solve
        request.meta.setdefault("impersonate", "safari_ios")  # clearance is for iPhone Safari
        request.headers["User-Agent"] = self.clearance["user_agent"]
        request.cookies = {**(request.cookies if isinstance(request.cookies, dict) else {}),
                           **self.clearance["cookies"]}       # includes cf_clearance
        return None

    def process_response(self, request, response, spider):
        if response.status == 403 and response.headers.get("cf-mitigated") == b"challenge":
            if not request.meta.get("nsl_retried"):
                self.clearance = None                         # expired: solve again
                retry = request.replace(dont_filter=True)
                retry.meta["nsl_retried"] = True
                return retry
        return response

# settings.py (with the scrapy-impersonate settings above)
# DOWNLOADER_MIDDLEWARES = {"myproject.middlewares.NSLClearanceMiddleware": 650}  # before CookiesMiddleware (700)
# NSLSOLVER_API_KEY = "YOUR_API_KEY"
# NSL_PROXY = "http://user:pass@sticky-proxy.example.com:8080"
# CF_SITE_KEY = "0x4AAAAAAA..."   # the challenge widget id

Full /solve API reference

When to use a solver API instead of tuning Scrapy

Steps 2 and 3 fix fingerprint problems; none of them fixes a challenge. If every request returns cf-mitigated: challenge, if you crawl many Cloudflare sites, or if a browser per worker is too expensive, a managed solver is simpler. NSLSolver's Cloudflare Challenge solver returns cf_clearance and the user_agent to replay in about 3.3 seconds on average for $1.00 per 1,000. Pages with a Turnstile widget on a form use the Turnstile solver instead: a token in about 250 ms for $0.80 per 1,000. Failed solves are not billed, and new accounts get free credit with Google, Gmail or Proton sign-up. Error 1020 blocks are firewall rules and cannot be solved by anyone. Only crawl sites you own or are authorised to access.

Related guides

Frequently asked questions

Why does Scrapy get 403 Forbidden on Cloudflare sites?

Usually the default User-Agent ("Scrapy/<version> (+https://scrapy.org)"), a TLS handshake that does not look like a browser, a low-reputation IP, or a JavaScript challenge Scrapy cannot run. Let the 403 reach your callback with handle_httpstatus_list and check the cf-mitigated header to see which.

What does "Ignoring response <403>: HTTP status code is not handled or not allowed" mean?

Scrapy's HttpErrorMiddleware filtered the 403 before your callback ran. It is not the cause of the block, only the log line for it. Allow the status temporarily with handle_httpstatus_list or HTTPERROR_ALLOWED_CODES to inspect the response.

Does scrapy-impersonate bypass Cloudflare?

It gives Scrapy a browser TLS/JA3 fingerprint through curl_cffi, which fixes 403s caused by the handshake. It does not execute JavaScript, so it cannot pass a challenge page; for that you need cf_clearance from a browser or a solver, replayed with a matching UA and IP.

Should I use scrapy-playwright for Cloudflare?

It can pass some challenges because it runs a real browser, but it is heavy and stock Playwright is detectable (see scrapy-playwright issue #203). Many crawls use the browser only to get cf_clearance and do the bulk fetching with plain Scrapy or scrapy-impersonate.

Does scrapy-cloudflare-middleware still work?

It was released once, in 2018, and depends on cfscrape, which was last released in 2020 for the old "Checking your browser" page. It is not a fix for current Cloudflare challenges.

How do I use cf_clearance in Scrapy?

Attach the cookie to every request from a downloader middleware placed before CookiesMiddleware, set the exact User-Agent that earned it, send everything through the same proxy, and use a TLS fingerprint from the same browser family. With NSLSolver's clearance that means the returned user_agent and scrapy-impersonate's safari_ios target.

Can NSLSolver fix Cloudflare error 1020 in Scrapy?

No. Error 1020 is a firewall rule that blocks the request outright; there is no challenge to solve. NSLSolver helps with JavaScript challenges (cf_clearance) and Turnstile widgets.

Keep Scrapy, skip the challenge

One POST returns cf_clearance and the matching User-Agent; your spider keeps doing the crawling. Free credit with Google, Gmail or Proton sign-up, no card needed.