Metadata-Version: 2.5
Name: scrapy-turnstile
Version: 0.2.2
Summary: Scrapy downloader middleware that solves Cloudflare Turnstile automatically via the Peak API.
Project-URL: Source, https://github.com/CircuitSavage/scrapy-turnstile
Project-URL: Homepage, https://peak.fo/?utm_source=github&utm_medium=readme&utm_campaign=packages&utm_content=scrapy-turnstile
Project-URL: Documentation, https://peak.fo/docs/turnstile?utm_source=github&utm_medium=pypi&utm_campaign=packages&utm_content=scrapy-turnstile
Project-URL: Pricing, https://peak.fo/?utm_source=github&utm_medium=pypi&utm_campaign=packages&utm_content=scrapy-turnstile#pricing
Author: Peak
License: MIT
License-File: LICENSE
Keywords: bypass,captcha,cloudflare,middleware,scrapy,solver,turnstile
Classifier: Framework :: Scrapy
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.8
Provides-Extra: scrapy
Requires-Dist: scrapy>=2.0; extra == 'scrapy'
Description-Content-Type: text/markdown

<a href="https://peak.fo/?utm_source=github&utm_medium=readme&utm_campaign=packages&utm_content=scrapy-turnstile">
  <img src="https://raw.githubusercontent.com/CircuitSavage/scrapy-turnstile/main/assets/peak-banner.png" alt="Peak: solve Cloudflare Turnstile and the 5-second challenge" width="100%">
</a>

# scrapy-turnstile

**scrapy-turnstile** is a Scrapy downloader middleware that solves Cloudflare Turnstile automatically. When a request hits a Turnstile-protected page, it detects the challenge, solves it through [Peak](https://peak.fo/?utm_source=github&utm_medium=readme&utm_campaign=packages&utm_content=scrapy-turnstile), and re-issues the request with the token so your spider gets the real page.

## Why

Scrapy makes plain HTTP requests. It has no JS engine, so a Turnstile-protected site returns a `403` or the "Just a moment..." interstitial instead of the content you asked for. The old `scrapy-cloudflare-middleware` only handled the legacy IUAM (I'm Under Attack Mode) JS challenge and is unmaintained; it does nothing for Turnstile, which is what Cloudflare now serves. cloudscraper has the same limitation: it can't solve Turnstile.

This middleware sends the Turnstile challenge to Peak and gets a token back. You add one entry to `DOWNLOADER_MIDDLEWARES` and set a Peak API key.

## Powered by Peak

This package uses [Peak](https://peak.fo/?utm_source=github&utm_medium=readme&utm_campaign=packages&utm_content=scrapy-turnstile) to solve Turnstile.
- Solves Cloudflare Turnstile and the 5-second challenge
- $0.90 per 1,000 successful Turnstile solves, down to $0.35 at volume
- You pay only for solves that land. 1,000 free solves to start, no card.
→ [Get your free API key](https://peak.fo/?utm_source=github&utm_medium=readme&utm_campaign=packages&utm_content=scrapy-turnstile) · [Docs](https://peak.fo/docs/turnstile?utm_source=github&utm_medium=readme&utm_campaign=packages&utm_content=scrapy-turnstile) · [Pricing](https://peak.fo/?utm_source=github&utm_medium=readme&utm_campaign=packages&utm_content=scrapy-turnstile#pricing)

## Install

```bash
pip install scrapy-turnstile
```

## Quickstart

Add the middleware to your project's `settings.py` and set your Peak key:

```python
# settings.py
DOWNLOADER_MIDDLEWARES = {
    "scrapy_turnstile.TurnstileMiddleware": 585,
}

PEAK_API_KEY = "pk_your_api_key"   # better: read from an env var
# PEAK_PROXY = "http://user:pass@ip:port"   # optional, routed to Peak
```

Or per-spider:

```python
import os
import scrapy


class ProtectedSpider(scrapy.Spider):
    name = "protected"
    start_urls = ["https://protected.example.com/"]

    custom_settings = {
        "DOWNLOADER_MIDDLEWARES": {
            "scrapy_turnstile.TurnstileMiddleware": 585,
        },
        "PEAK_API_KEY": os.environ["PEAK_API_KEY"],
    }

    def parse(self, response):
        # The challenge, if any, was already solved upstream.
        yield {"title": response.css("title::text").get()}
```

```bash
export PEAK_API_KEY=pk_your_api_key
scrapy runspider examples/quotes_spider.py
```

A runnable spider is in [`examples/quotes_spider.py`](examples/quotes_spider.py).

## How it works

1. `process_response` inspects every response for Turnstile markers (`cf-turnstile`, the `challenges.cloudflare.com/turnstile` script, the "Just a moment" interstitial).
2. On a match it extracts the `data-sitekey` and the request URL.
3. It calls Peak: `POST https://api.peak.fo/solve` with `{"task_type": "turnstiletask", "sitekey": ..., "url": ...}` and header `X-API-Key`.
4. It re-issues the original request with the returned token injected as the `cf-turnstile-response` form field, and also on `request.meta["cf_turnstile_response"]` for custom submits.
5. A `meta` flag stops the retried request from being re-processed, so there are no loops.

Peak also supports the Cloudflare 5s interstitial via `task_type: "cloudflare5stask"`.

## Settings

| Setting | Default | Purpose |
| --- | --- | --- |
| `PEAK_API_KEY` | (required) | Your Peak key, format `pk_...`. |
| `PEAK_PROXY` | `None` | Proxy string forwarded to Peak so the solve matches your crawl IP. |
| `PEAK_API_URL` | `https://api.peak.fo/solve` | Override the solve endpoint. |
| `PEAK_APP_ID` | `None` | Optional app id sent as `appId` to earn revenue share on each solve. |
| `PEAK_TURNSTILE_FIELD` | `cf-turnstile-response` | Form field the token is injected into. |
| `PEAK_TURNSTILE_MAX_RETRIES` | `2` | Max solve attempts per request before giving up. |

## Earn with your app ID

Set `PEAK_APP_ID` in your Scrapy settings to earn 5% of every solve your spider makes, paid as Peak solve credit. It is optional and does not change whether a solve succeeds or how fast it returns.

```python
# settings.py
PEAK_APP_ID = "app_your_id"   # optional; earns solve credit on each solve
```

Create an app id at [peak.fo/dashboard/developer](https://peak.fo/dashboard/developer); details at [peak.fo/earn](https://peak.fo/earn).

## Troubleshooting

The middleware never raises into your spider. It writes to the `scrapy_turnstile` logger and hands the blocked response back, so read the crawl log first.

- **`Disabled scrapy_turnstile.TurnstileMiddleware: PEAK_API_KEY is not set.`** Scrapy printed this at startup and dropped the middleware, so every challenge page reaches your callback untouched. Set `PEAK_API_KEY` in `settings.py` or in the spider's `custom_settings`. Keys start with `pk_`; the free one comes from the [dashboard](https://peak.fo/?utm_source=github&utm_medium=readme&utm_campaign=packages&utm_content=scrapy-turnstile).
- **`Turnstile challenge detected on <url> but no sitekey found.`** The body carried a Cloudflare marker and no `data-sitekey`. Two causes. The page is the managed "Just a moment..." interstitial, which wants a `cf_clearance` cookie and has no widget sitekey in its HTML; [Turnstile token vs cookie](https://blog.peak.fo/cloudflare-turnstile-token-vs-cookie/) and [the Cloudflare 5-second challenge explained](https://blog.peak.fo/the-cloudflare-5-second-challenge-explained/) cover that check. Or the site builds the widget with `turnstile.render()` inside a script bundle that Scrapy never runs. [How to find a Cloudflare Turnstile sitekey](https://blog.peak.fo/how-to-find-a-cloudflare-turnstile-sitekey/) shows where sites hide the key; once you have it, call `PeakClient(api_key).solve(sitekey, url)` from your callback.
- **`Peak failed to solve <url>: Peak request failed: ...`** The request never reached Peak. Check DNS, the firewall, and any `HTTPS_PROXY` variable in the environment, since `urllib` honours it.
- **`Peak failed to solve <url>:` followed by Peak's own reason, or `Peak solve failed`.** Peak answered with `success: false`. Common causes: an empty balance, a sitekey that does not belong to the URL, or a `PEAK_PROXY` Peak could not connect through. Peak does not bill a failed solve. The [Cloudflare Turnstile error codes](https://blog.peak.fo/cloudflare-turnstile-error-codes/) post covers the widget-side codes (110200, 300030, 600010 and the rest).
- **The log says `solving via Peak` and your callback still gets the challenge page.** The middleware retries by sending the token as a `POST` to the URL that returned the challenge. Many sites check the token at a different endpoint, such as the form's `action` or an XHR route. The token is also on `response.meta["cf_turnstile_response"]`, so build the real submit yourself with `scrapy.FormRequest`. A token is single-use and expires 300 seconds after Cloudflare issues it. [The cf-turnstile-response token explained](https://blog.peak.fo/the-cf-turnstile-response-token-explained/) covers the field.
- **`Ignoring response <403 ...>: HTTP status code is not handled or not allowed`.** The retried request came back 403 and Scrapy's `HttpErrorMiddleware` dropped it before your callback ran. Add `handle_httpstatus_list = [403]` to the spider to inspect the body. Set `PEAK_PROXY` to the proxy your crawl uses so Peak mints the token from the address that submits it. [Cloudflare Turnstile 403](https://blog.peak.fo/cloudflare-turnstile-403-scraper-fix/) covers the refusal.

Two longer reads for this stack: [How to scrape Cloudflare-protected sites without getting blocked](https://blog.peak.fo/how-to-scrape-cloudflare-protected-sites-without-getting-blocked/) and the [2026 Turnstile developer guide](https://blog.peak.fo/how-to-solve-cloudflare-turnstile-in-2026-dev-guide/).

## Related

Same pattern for other stacks: [cloudscraper-turnstile](https://github.com/CircuitSavage/cloudscraper-turnstile) (a `requests.Session` drop-in, no browser) · [turnstile-curl](https://github.com/CircuitSavage/turnstile-curl) · [scrapling-turnstile](https://github.com/CircuitSavage/scrapling-turnstile) · [playwright-turnstile](https://github.com/CircuitSavage/playwright-turnstile) · [patchright-turnstile](https://github.com/CircuitSavage/patchright-turnstile) · [selenium-turnstile](https://github.com/CircuitSavage/selenium-turnstile) · [nodriver-turnstile](https://github.com/CircuitSavage/nodriver-turnstile) · [camoufox-turnstile](https://github.com/CircuitSavage/camoufox-turnstile) · [pydoll-turnstile](https://github.com/CircuitSavage/pydoll-turnstile) · [drissionpage-turnstile](https://github.com/CircuitSavage/drissionpage-turnstile) · [botasaurus-turnstile](https://github.com/CircuitSavage/botasaurus-turnstile) · [crawlee-turnstile](https://github.com/CircuitSavage/crawlee-turnstile) · [puppeteer-extra-plugin-turnstile](https://github.com/CircuitSavage/puppeteer-extra-plugin-turnstile) · [browser-use-turnstile](https://github.com/CircuitSavage/browser-use-turnstile) · [crawl4ai-turnstile](https://github.com/CircuitSavage/crawl4ai-turnstile). Full list in [awesome-turnstile-solvers](https://github.com/CircuitSavage/awesome-turnstile-solvers).

[cloudflare-turnstile-reversed](https://github.com/CircuitSavage/cloudflare-turnstile-reversed) documents the challenge flow, the widget parameters and the fingerprinting the widget runs before it hands out a token.

## Legitimate use

For automation, QA, and scraping public data you are allowed to access. Respect each target's Terms of Service and `robots.txt`, and rate-limit yourself. Do not use this for credential stuffing or to access data you have no right to.

## License

MIT. See [LICENSE](LICENSE).
