Integration guide
Scrapy integration: middleware and settings
Scrapy is built for plain HTTP, and so is GateSolver, which makes the pairing natural: a downloader middleware solves challenges inside the crawl without a browser. This guide sets one up from settings to scale.
Where the solver belongs in a crawl
Put the solving code in a downloader middleware. Every response passes through the middleware chain before your spider sees it, and a middleware may return a different request in place of the response. That lets it notice a challenge page, get an answer from the API, and schedule the form submission, while the spider's callbacks stay focused on extracting data.
The design here is opt-in. A request carries a small gatesolver entry in its meta that says which widget to expect, which field receives the answer and which form to submit. Requests without it pass through untouched, so the middleware never spends money on pages you did not mark. Our blog post on a detection based middleware takes the other approach and recognizes challenges automatically; both fit, and you can combine them.
Requirements and settings
You need Scrapy 2.x running on the asyncio reactor (recent releases use it by default; older projects set it in settings.py), and pip install aiohttp for the async HTTP calls. Scrapy accepts async def process_response in downloader middlewares, so a solve that waits a few seconds does not block other downloads. Version details change, so check the coroutine section of the Scrapy docs for your release.
# settings.py
import os
TWISTED_REACTOR = "twisted.internet.asyncioreactor.AsyncioSelectorReactor" # default in new projects
DOWNLOADER_MIDDLEWARES = {"shop_watch.gatesolver_mw.GateSolverMiddleware": 585}
GATESOLVER = {
"api_key": os.environ.get("GATESOLVER_KEY", "YOUR_API_KEY"),
"max_rounds": 2, # solves per request before giving up
"poll_seconds": 3,
}
CONCURRENT_REQUESTS_PER_DOMAIN = 4
AUTOTHROTTLE_ENABLED = True
COOKIES_ENABLED = True
The order value 585 places the middleware after redirects are followed (the redirect middleware sits at 600) and before the retry middleware at 550, so it sees final pages and its own resubmissions are not mistaken for network failures. Cookies stay on because sites often link the form submission to cookies set on the first visit.
The middleware
import asyncio, aiohttp # shop_watch/gatesolver_mw.py
from scrapy.exceptions import IgnoreRequest, NotConfigured
from scrapy import FormRequest
class GateSolverMiddleware:
def __init__(self, cfg, stats):
if not cfg.get("api_key"):
raise NotConfigured("GATESOLVER api_key is empty")
self.cfg, self.stats = cfg, stats
from_crawler = classmethod(lambda cls, c: cls(c.settings.getdict("GATESOLVER"), c.stats))
async def answer(self, task):
key, wait = self.cfg["api_key"], self.cfg.get("poll_seconds", 3)
async with aiohttp.ClientSession(base_url="https://gatesolver.com") as http:
async def gate(route, body):
async with http.post(route, json={"clientKey": key, **body}) as resp:
return await resp.json(content_type=None)
opened = await gate("/createTask", {"task": task})
if int(opened.get("errorId") or 0):
raise IgnoreRequest(f"createTask: {opened.get('errorCode')}")
for _ in range(int(125 / wait)):
await asyncio.sleep(wait)
current = await gate("/getTaskResult", {"taskId": opened["taskId"]})
if current.get("status") == "ready":
return current["solution"]
if current.get("errorId") or current.get("status") == "failed":
break
raise IgnoreRequest(f"no answer for {task['websiteURL']}")
async def process_response(self, request, response, spider): # runs for every response
spec = request.meta.get("gatesolver")
widget = response.css(spec["widget"]) if spec else None
rounds = request.meta.get("gs_rounds", 0)
if not widget:
return response
if rounds >= self.cfg.get("max_rounds", 2):
raise IgnoreRequest(f"challenge persists on {response.url}")
sol = await self.answer({"type": spec["type"], "websiteURL": response.url,
"websiteKey": widget.attrib.get("data-sitekey")})
self.stats.inc_value(f"gatesolver/solved/{spec['type']}")
return FormRequest.from_response(response, formcss=spec.get("form", "form"),
formdata={spec["field"]: sol.get("gRecaptchaResponse") or sol.get("token")},
callback=request.callback, errback=request.errback, dont_filter=True,
meta={**request.meta, "gs_rounds": rounds + 1})
Each solve opens a short lived HTTP session, which keeps the class free of startup and shutdown hooks. For crawls that solve constantly, you can hold one ClientSession on the instance and close it from a spider_closed signal handler instead.
Marking requests in the spider
A spider opts in per request. The meta entry is plain data, so you can keep a dictionary of specs per site and reuse it.
TURNSTILE_FORM = {"type": "AntiTurnstileTaskProxyLess", "widget": ".cf-turnstile[data-sitekey]",
"field": "cf-turnstile-response", "form": "form#lookup"}
async def start(self):
for sku_url in self.sku_pages:
yield scrapy.Request(sku_url, callback=self.parse_price,
meta={"gatesolver": TURNSTILE_FORM})
The async def start() method arrived in Scrapy 2.13; on older versions put the same loop in start_requests, and the meta works identically. For a reCAPTCHA v2 form, use ReCaptchaV2TaskProxyLess, the selector .g-recaptcha[data-sitekey] and the field g-recaptcha-response.
How the answer reaches the site
FormRequest.from_response reads the form on the challenge page, keeps its hidden inputs (CSRF values, tokens of the site's own), adds the answer, and posts to the form's action URL. The site usually redirects back to the page you asked for, the redirect middleware follows it, and your callback receives the real content. If the answer is a cookie rather than a form field, as with AWS WAF, return request.replace(cookies=...) with the cookie instead of a form request; the cookie middleware then keeps sending it for later pages on that site.
Errors and what the crawl does with them
The middleware raises IgnoreRequest in three cases: the API refused the task, the task did not finish, or the page still shows the widget after the configured number of rounds. Scrapy drops the request and calls its errback if one is set, so you can log the URL for a later run. Failed tasks are free, which makes max_rounds = 2 a sensible default. For key or balance errors, consider closing the spider instead with CloseSpider, because every following request would hit the same wall. The crawl stats at the end show gatesolver/solved/... counters per task type; a sudden rise is the first sign that a site changed its protection.
Testing without a live site
Most of the middleware can be tested offline. Save a challenge page from your target as an HTML file, build an HtmlResponse from it with a matching Request that carries your meta spec, and assert that response.css(spec["widget"]) finds the container and that its data-sitekey is read. To test the form step, replace answer on the instance with a coroutine that returns a fake solution, run process_response with asyncio.run or your test runner's async support, and check that the returned FormRequest posts to the right URL with the field set. The live API then only needs a single end to end run against a page you control.
Proxy tasks and sticky IPs
If the crawl sends traffic through proxies, some sites accept a token only from the IP that loaded the form. Read the proxy from request.meta["proxy"], switch the task to the proxy variant (ReCaptchaV2Task rather than the proxyless type) and pass the same proxy in the task's proxy field. Keep each site on a sticky proxy for the length of a session, because a cookie earned on one IP and replayed from another is a common reason for repeated challenges. Our glossary entry on sticky sessions explains the idea.
Concurrency and cost
While a solve waits, the coroutine yields and Scrapy keeps downloading other pages, so a few slow tasks do not stall the crawl. The ceiling to plan for is the API's 600 requests per minute per key: each task takes one create call and several polls. With CONCURRENT_REQUESTS_PER_DOMAIN around 4 and AutoThrottle on, most crawls stay far below it. Turnstile tasks cost $0.84 per 1,000 and reCAPTCHA v2 $0.56, so the cheapest solve remains the one you avoid by pacing requests politely. When a site needs JavaScript rendering, Scrapy with Playwright shows how to combine the two. Keep crawls to public data, respect robots rules, and treat a challenge as a request to slow down.
Common questions
Does the middleware need a browser?
No. Scrapy fetches the page, GateSolver returns the token over HTTP, and the form is posted by Scrapy; no browser is involved.
Why is the middleware opt-in through request meta?
It keeps solving limited to pages you expect to carry a widget, so an unrelated form on another page never triggers a paid task.
Which order number should I use?
A value between the retry middleware (550) and the redirect middleware (600) lets it see final pages; 585 is used here.
Can I use httpx instead of aiohttp?
Yes. Any asyncio HTTP client works the same way; aiohttp is simply a common choice in Scrapy projects that already run on the asyncio reactor.
What happens to requests the middleware gives up on?
They raise IgnoreRequest, Scrapy drops them and calls the errback if one is set, so you can record the URL.
Keep reading
- Handle CAPTCHAs in a Scrapy middlewareAn async downloader middleware that spots a challenge response, solves it through the API and reschedules the request, keeping spiders clean.
- Scrapy with PlaywrightRender only the requests that need JavaScript: scrapy-playwright settings, page methods, page objects, contexts and blocking heavy resources.
- ScrapyThe Python crawling framework built on spiders, a scheduler and middlewares, made for large structured crawls.
- reCAPTCHA v2 solver$0.56 per 1,000 tasks, answers under 9 seconds.