CAPTCHA basics
Solving CAPTCHAs in web scraping pipelines
In a scraper, a CAPTCHA should be a planned outcome with its own path through the system, not an exception buried in a parser. This article lays out a detect, solve and retry architecture that stays simple as volume grows.
The core idea
Treat every fetch as producing one of three outcomes: content, challenge or error. Content goes to parsing. Errors go to a retry policy. Challenges go to a solver stage that returns either a usable answer or a decision to give up. Keeping the three paths separate is what makes a pipeline debuggable, because each kind of failure has its own counter, logs and limits.
Many scrapers instead let a challenge page flow into the parser, which then finds no data and quietly records an empty result. That is the worst outcome: wrong data with no alarm. The first job of the architecture is to stop that from happening.
Stage one: detect
Detection runs right after every fetch and classifies the response. Signals worth checking, from cheapest to most expensive:
- Status code.
403,429and503on pages that normally return200. - Headers and cookies. Protection layers set recognizable cookies and headers when they intervene.
- Markup markers. A
data-sitekeyattribute, an iframe from a CAPTCHA vendor, a known check page title, or a script from a challenge domain. - Content sanity. A product page without a price, a result list with zero items for a common query, or a body far shorter than usual.
The detector's output is a small record: the outcome, and for challenges, the type and the fields a task will need. The guide to identifying Cloudflare protection shows the markers for one major vendor; identifying the reCAPTCHA version does the same for Google's family.
def classify(resp_status: int, html: str) -> dict:
if 'name="cf-turnstile-response"' in html or "cf-turnstile" in html:
key = extract_attr(html, "data-sitekey")
return {"outcome": "challenge", "kind": "AntiTurnstileTaskProxyLess", "key": key}
if "g-recaptcha" in html and "data-sitekey" in html:
key = extract_attr(html, "data-sitekey")
return {"outcome": "challenge", "kind": "ReCaptchaV2TaskProxyLess", "key": key}
if resp_status in (403, 429, 503):
return {"outcome": "error", "retry_after": 30}
return {"outcome": "content"}
Real detectors check more markers than this sketch, but the shape is the point: one function, one small result, no parsing.
Stage two: solve
The solver stage turns a challenge record into an answer. Keep it separate from fetching so it can run concurrently and be measured on its own. Its steps:
- Build the task from the record: type, page URL, site key, and type-specific fields such as
pageActionor a proxy. - Create the task, then poll every few seconds until it is ready or failed.
- Return the answer with its metadata (task id, user agent, the time it was produced), or a failure reason.
Because solving is asynchronous and there is no limit on concurrent tasks, the solver stage can hold many tasks at once while fetchers keep working on other URLs. In an async crawler, each challenged URL simply awaits its solve; in a queue-based system, challenged URLs go to a solver queue and come back to the fetch queue with an answer attached. The Scrapy middleware article shows one concrete implementation of this split.
Use the answer immediately
A token lives for minutes and is accepted a single time. The answer should flow straight back to the fetcher that will submit it, not into a shared pool for later. For cookie answers, attach the cookie to the session that will reuse it, with the same proxy and user agent, and let it serve every following request in that session.
Stage three: retry with limits
Retries are where pipelines go wrong, usually by retrying forever. Set explicit limits for each path:
| Situation | Action | Limit |
|---|---|---|
| Network error or timeout | Retry the fetch with backoff | A few attempts |
| 429 or 503 with Retry-After | Wait, then retry, and slow that host | Until the window passes |
| Task failed or unsolvable | Create a fresh task | One or two times |
| Solver service unavailable | Wait a few seconds, retry | A few attempts |
| Answer rejected by the site | Re-fetch the page, solve again with a fresh session | Once, then flag |
| Challenge reappears right after a valid answer | Stop solving; retire the session or address | No retry |
| Zero balance or key denied | Stop the solver stage and alert | No retry |
The last two rows matter most. A challenge that returns immediately after a valid answer means the site distrusts the session, not the answer; solving again just spends money. Configuration errors will not fix themselves, so the pipeline should halt cleanly and tell someone. The error handling guide lists each solver error code with the right reaction.
Keep solves rare
The cheapest solve is the one you avoid. Feed the detector's counts back into pacing: when the challenge rate for a host rises, reduce concurrency for that host. Keep sessions long enough that one clearance cookie covers many pages. Cache responses so reruns do not fetch again. A healthy pipeline sees challenges as an occasional event, not a constant tax; if solving dominates the run, the problem is upstream.
Observe everything
Each stage should emit metrics with the host as a label:
- Outcomes per 1,000 fetches: content, challenge, error.
- Solves started, succeeded, failed, and the time to answer.
- Answers rejected by the site after submission.
- Cost per day, summed from the
costfield of each ready task.
Store the task id with every record produced after a solve. When a site starts rejecting answers, you can trace exact tasks, timings and parameters instead of guessing.
Where to run the browser
Pipelines that mostly use plain HTTP clients can still need a browser for some challenges, for example to click image grid tiles or drag a slider. Keep that browser work in a small dedicated pool rather than rendering every page. Token and cookie answers usually do not need a browser at all: you can submit tokens with an HTTP client and attach cookies to its session, provided the client's fingerprint and user agent match what the answer expects.
Scaling the design
The same three stages work from a single script to a distributed system. In a script, they are three functions. In a crawler framework, they are a middleware or a hook. At larger scale, they become separate services connected by queues, with the solver stage sized by the number of tasks in flight and the 600 requests per minute per key limit in mind. Because the balance is shared across types and there is no limit on concurrent tasks, scaling up means mostly adding fetchers and keeping polling efficient.
Keep the scope to collection you are entitled to do: public pages, at a considerate rate, without personal data you do not need. That keeps both the pipeline and its purpose easy to defend.
Common questions
Where should CAPTCHA detection live in a scraper?
Right after the fetch and before the parser, as a classifier that labels each response as content, challenge or error.
Should the parser handle challenge pages?
No. If challenge pages reach the parser they become empty or wrong records. Detect and route them before parsing.
How many times should a failed solve be retried?
Once or twice with a fresh task. If answers are accepted but the challenge returns, retire the session instead of solving again.
Can one solver stage serve many crawlers?
Yes. There is no limit on concurrent tasks; just keep the total request rate per API key under 600 per minute.
Do I need a browser to use solved tokens?
Not usually. Tokens and cookies can be submitted from an HTTP client whose fingerprint and user agent match the answer.
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.
- What does a solid scraping pipeline look like?Discovery, fetching, parsing, validation and delivery as separate stages, joined by queues and storage so each can fail safely.
- Error handling for CAPTCHA APIsSort every CAPTCHA API error into retry, fix or stop, follow those rules in code, and know which outcomes cost nothing.
- Request queueThe list of URLs a crawler still has to visit, with retries, priorities and deduplication built into how it is stored.