NEWStandard createTask and in.php APIs. Change the address and you are connected.View API docs
GATESOLVER

Web scraping

How to handle CAPTCHAs in a Scrapy middleware

Spiders should parse data, not fight challenge pages. A downloader middleware can watch every response, solve a CAPTCHA when one appears and send the request again, so the rest of your project never knows it happened.

Why a downloader middleware

Scrapy passes every response through a chain of downloader middlewares before it reaches your spider. A middleware's process_response method can return the response unchanged, or return a new Request, which Scrapy schedules instead. That second option is exactly what a CAPTCHA handler needs: recognise the challenge, get an answer, and replace the blocked response with a fresh request that carries the answer. Spiders keep their callbacks simple, and the logic lives in one tested place.

This guide handles two common cases. The first is an interstitial page with a reCAPTCHA v2 form that the site wants you to submit before it shows the content. The second is the AWS WAF puzzle page, which is answered with a cookie. Adding more types follows the same pattern.

Requirements

  • Scrapy 2.x with the asyncio reactor. Projects generated by recent versions of scrapy startproject already set TWISTED_REACTOR to the asyncio reactor, and newer releases use it by default; check your settings.py.
  • An async HTTP client for the API calls. The example uses HTTPX (pip install httpx); aiohttp works the same way.
  • Your API key in a setting or environment variable.

Scrapy allows process_response to be a coroutine (async def). While a solve is waiting, the engine keeps downloading and parsing other requests, so one challenge does not stall the crawl. Method signatures here follow Scrapy 2.11 to 2.13; check the release notes if you are on a newer version.

Detecting a challenge

Detection should be cheap and specific. Look for markers that only a challenge page has, and avoid matching ordinary pages that merely include a CAPTCHA somewhere in a footer form.

# detect.py
def challenge_kind(response):
    if response.status == 405 and b"gokuProps" in response.body:
        return "aws-waf"
    if b"g-recaptcha" in response.body:
        key = response.css("form .g-recaptcha::attr(data-sitekey)").get()
        if key and response.css("form[action*='verify'], form#challenge-form"):
            return "recaptcha-form"
    return None

The form selector is an example: open a real challenge page from your target in DevTools and write a selector that matches its form and nothing else. Checking bytes first (b"g-recaptcha" in response.body) keeps the cost near zero on normal pages, because CSS parsing only runs when the marker is present.

The solver coroutine

Keep the API code small and separate. It takes a task dictionary and returns the solution, raising on errors and on failed tasks.

# gate_async.py
import asyncio
import httpx

async def run_task(task: dict, api_key: str, wait_s: float = 3.0) -> dict:
    async with httpx.AsyncClient(base_url="https://gatesolver.com", timeout=30) as api:
        opened = (await api.post("/createTask", json={"clientKey": api_key, "task": task})).json()
        if opened.get("errorId"):
            raise RuntimeError(opened.get("errorCode"))
        for _ in range(int(125 / wait_s)):
            await asyncio.sleep(wait_s)
            got = (await api.post("/getTaskResult",
                                  json={"clientKey": api_key, "taskId": opened["taskId"]})).json()
            if got.get("errorId") or got.get("status") == "failed":
                raise RuntimeError(got.get("errorCode", "task failed"))
            if got.get("status") == "ready":
                return got["solution"]

If the loop finishes without a result, the function returns None, which the middleware treats as "give up on this request". That keeps timeouts out of the exception path.

The middleware

# middlewares.py
from scrapy.exceptions import IgnoreRequest
from scrapy.http import FormRequest
from .detect import challenge_kind
from .gate_async import run_task

class ChallengeSolverMiddleware:
    def __init__(self, api_key, limit):
        self.api_key, self.limit = api_key, limit

    @classmethod
    def from_crawler(cls, crawler):
        conf = crawler.settings
        return cls(conf.get("GATESOLVER_API_KEY"), conf.getint("CHALLENGE_SOLVE_LIMIT", 2))

    async def process_response(self, request, response, spider):
        kind = challenge_kind(response)
        if kind is None:
            return response
        tries = request.meta.get("challenge_tries", 0)
        if tries >= self.limit:
            raise IgnoreRequest(f"challenge persists on {request.url}")
        meta = {**request.meta, "challenge_tries": tries + 1}
        spider.crawler.stats.inc_value(f"challenge/{kind}")
        if kind == "aws-waf":
            sol = await run_task({"type": "AntiAwsWafTaskProxyLess", "websiteURL": response.url}, self.api_key)
            if not sol:
                raise IgnoreRequest("no AWS WAF cookie")
            return request.replace(cookies={**request.cookies, "aws-waf-token": sol["cookie"]},
                                   meta=meta, dont_filter=True)
        site_key = response.css("form .g-recaptcha::attr(data-sitekey)").get()
        sol = await run_task({"type": "ReCaptchaV2TaskProxyLess", "websiteURL": response.url,
                              "websiteKey": site_key}, self.api_key)
        if not sol:
            raise IgnoreRequest("no reCAPTCHA token")
        return FormRequest.from_response(
            response, formdata={"g-recaptcha-response": sol["gRecaptchaResponse"]},
            callback=request.callback, errback=request.errback, meta=meta, dont_filter=True)

Three details make this robust:

  • A retry counter in meta. If the site keeps showing the challenge, the request is dropped after the limit instead of looping and spending money.
  • dont_filter=True on the new request. Without it, Scrapy's duplicate filter would discard the retry because the URL was already seen.
  • Stats. challenge/aws-waf and challenge/recaptcha-form counters appear in the crawl's final stats, so you can see how often each check fired.

For the AWS WAF case the cookie is added to request.cookies; Scrapy's cookie middleware stores it in the session jar, so later requests to the same site carry it automatically until it expires. For the form case, FormRequest.from_response copies the form's hidden fields and posts them with the token; the site typically redirects back to the original page, and Scrapy follows that redirect to your callback.

Enabling it

# settings.py (the asyncio reactor must already be active, see above)
DOWNLOADER_MIDDLEWARES = {
    "myproject.middlewares.ChallengeSolverMiddleware": 560,
}
GATESOLVER_API_KEY = "YOUR_API_KEY"
CHALLENGE_SOLVE_LIMIT = 2
COOKIES_ENABLED = True

The order number decides where the middleware sits. Downloader middlewares handle responses from the highest number to the lowest, so 560 runs after the built in redirect handling (600) has finished and before the retry middleware (550) sees the response. In production, read the key from the environment, for example with os.environ["GATESOLVER_API_KEY"] in settings.py, rather than committing it.

Testing the middleware

You can test detection without any network: build an HtmlResponse from a saved challenge page and assert that challenge_kind returns the right label. For the full flow, point a small spider at one known challenge URL with CLOSESPIDER_PAGECOUNT set low and watch the log. You should see the challenge response, a pause while the task runs, then the rescheduled request and your callback's items. The stats at the end confirm how many solves happened.

Keeping solves rare

A middleware like this is a safety net, not a strategy. The best crawls rarely trigger it, because they look and behave like considerate traffic:

  • Turn on AutoThrottle and set a modest CONCURRENT_REQUESTS_PER_DOMAIN.
  • Send a realistic User-Agent and Accept-Language, consistent for the whole crawl.
  • Reuse sessions: once a cookie is earned, let it carry many requests.
  • If one IP keeps hitting challenges, slow down or change it rather than solving on every page.

Watch the challenge/* stats over time. A sudden jump means the site changed something, and that is the moment to review pacing before the bill grows.

Proxies and sticky sessions

If you send traffic through proxies, some sites only accept a token or cookie from the IP that earned it. In that case switch to the proxy versions of the task types (ReCaptchaV2Task, AntiAwsWafTask) and pass the same proxy that the request used, which you can read from request.meta["proxy"]. Keep a sticky proxy per session so the cookie and the IP stay paired; our note on rotating or sticky proxies explains why.

Use this for public data collection, price monitoring and QA crawls of your own sites. Respect robots.txt and keep request rates gentle; a challenge page is often a site's polite way of asking you to slow down.

The Scrapy integration page summarizes setup for other CAPTCHA types, and Scrapy with Playwright covers pages that need a real browser.

Common questions

Can process_response be async in Scrapy?

Yes. Downloader middleware methods can be coroutines in Scrapy 2.x; with the asyncio reactor you can await asyncio based clients such as HTTPX.

Does a solve block the whole crawl?

No. While the coroutine waits for the task, Scrapy keeps downloading and parsing other requests.

Why is dont_filter needed on the retried request?

The URL was already seen, so the duplicate filter would drop the retry. dont_filter tells the scheduler to accept it.

Where should the middleware sit in the order?

Around 560 works well: responses reach it after redirect handling and before the retry middleware.

How do I stop endless solving on one URL?

Count attempts in request.meta and raise IgnoreRequest once the limit is reached, as the example does.

Keep reading