Integration guide
Crawl4AI integration: solving inside crawler hooks
Crawl4AI runs a real browser and exposes hooks at each stage of a crawl. Two of those hooks are all you need to answer a CAPTCHA before the page content is extracted.
Where solving fits in a Crawl4AI run
Crawl4AI opens a page in a Playwright controlled browser, waits for it, and turns the final HTML into clean markdown or structured data for your pipeline. Hooks let your code run at fixed points of that process. For CAPTCHAs, two points matter: right after navigation, when a widget is visible and can be answered in the page, and before navigation, when you already know the site will want a cookie and can add it to the browser context in advance. Both hooks call the GateSolver HTTP API the same way; there is no Crawl4AI plugin from us and none is needed.
Setup and hook names by version
Install with pip install crawl4ai httpx, then run the setup command the project documents (crawl4ai-setup at the time of writing) to download the browser. Hook names and signatures have been fairly stable across recent releases, but Crawl4AI is under active development, so open the hooks page of the docs for your version and compare: the examples assume crawler.crawler_strategy.set_hook(name, fn) and async hook functions that receive the Playwright page and context as keyword arguments and return the page.
Answering a widget after navigation
The after_goto hook runs once the page has loaded and before Crawl4AI collects its HTML. If a Turnstile or reCAPTCHA form stands between you and the content, the hook can read the key, solve, place the token, submit, and wait for the next page. Crawl4AI then extracts the page that loaded after the submit.
import asyncio, os
import httpx
from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig, CacheMode
C4_API = "https://gatesolver.com"
async def gs_answer(task: dict) -> dict | None:
async with httpx.AsyncClient(base_url=C4_API, timeout=30) as api:
auth = {"clientKey": os.environ["GATESOLVER_KEY"]}
made = (await api.post("/createTask", json={**auth, "task": task})).json()
if made.get("errorId"):
print("createTask refused:", made.get("errorCode")); return None
for _ in range(40):
await asyncio.sleep(3)
seen = (await api.post("/getTaskResult", json={**auth, "taskId": made["taskId"]})).json()
if seen.get("status") == "ready":
return seen["solution"]
if seen.get("errorId") or seen.get("status") == "failed":
return None
return None
async def after_goto(page, context, url, response, **kwargs):
box = await page.query_selector(".cf-turnstile[data-sitekey]")
if box is None:
return page # nothing to answer, crawl as usual
sol = await gs_answer({"type": "AntiTurnstileTaskProxyLess", "websiteURL": page.url,
"websiteKey": await box.get_attribute("data-sitekey")})
if sol:
await page.eval_on_selector("[name='cf-turnstile-response']",
"(el, v) => { el.value = v; }", sol["token"])
async with page.expect_navigation():
await page.click("form#lookup [type=submit]")
return page
async def main():
run_cfg = CrawlerRunConfig(cache_mode=CacheMode.BYPASS, session_id="catalog")
async with AsyncWebCrawler(config=BrowserConfig(headless=True)) as crawler:
crawler.crawler_strategy.set_hook("after_goto", after_goto)
result = await crawler.arun("https://example.com/catalog/lookup", config=run_cfg)
print(result.success, str(result.markdown)[:300])
asyncio.run(main())
The hook returns the page in every branch, which Crawl4AI expects. CacheMode.BYPASS stops a cached copy of the challenge page from being reused, and session_id keeps the same browser tab for later arun calls, so cookies earned by the submit carry over to the next pages of the site.
Preloading a cookie before navigation
Some protections answer with a cookie rather than a form field. AWS WAF is the clearest case: the solution is a value you set as the aws-waf-token cookie. When you know a site uses it, solve before the first request and add the cookie to the browser context in the on_page_context_created hook, so the first page load already carries it.
import urllib.parse as up
TARGET = "https://shop.example.com/category/monitors"
async def preload_waf_cookie(page, context, **kwargs):
sol = await gs_answer({"type": "AntiAwsWafTaskProxyLess", "websiteURL": TARGET})
if sol and sol.get("cookie"):
await context.add_cookies([{
"name": "aws-waf-token", "value": sol["cookie"],
"domain": up.urlsplit(TARGET).hostname, "path": "/",
}])
return page
# inside main(), before arun():
# crawler.crawler_strategy.set_hook("on_page_context_created", preload_waf_cookie)
If the WAF page carries key, iv and context values, pass them as awsKey, awsIv and awsContext for the task; our guide to finding AWS WAF parameters shows where they appear. For the Cloudflare check screen, the same preload pattern works with an AntiCloudflareTask, but that cookie only works from the proxy IP used for the task, so the crawler's BrowserConfig must use the same proxy and the userAgent from the solution.
Hooks or js_code?
Crawl4AI also accepts js_code in the run config, which executes JavaScript in the page after load. That is handy for clicking a "load more" button, but it cannot wait for an external API in Python, so it is the wrong place for solving. Hooks run your Python code with the live page object, which lets you make the API call, wait for the answer and then touch the page. A useful split is to keep site interactions that need no answer in js_code and put solving in after_goto, so each part stays small.
Debugging hooks
Run with BrowserConfig(headless=False) while developing so you can watch the hook work, and add verbose=True to see Crawl4AI's own log lines around each stage. Print from the hook at entry and exit with the URL; if the entry line never appears, the hook name or registration is wrong for your version. If the hook runs but the markdown still shows the challenge, check that the submit actually navigated: some forms post through JavaScript without a page load, in which case wait for a selector from the real content instead of a navigation.
Finding widget values inside a hook
Inside a hook you have the full Playwright page, so every method from our Playwright guide applies: query_selector for data-sitekey, wait_for_selector for widgets injected late, or listening to requests for keys that only appear in widget URLs. Keep detection cheap: a single selector check on pages without a widget adds almost nothing to crawl time.
For widgets that appear only after a click or a scroll, run that interaction first inside the hook, then wait for the container with page.wait_for_selector(".cf-turnstile[data-sitekey]", timeout=10000) wrapped in a try block, so pages without a widget still continue quickly.
Errors and retries
The helper returns None on any failure, and the hook then returns the page unchanged, so the crawl still finishes and result.html contains the challenge page. Detect that in your pipeline (look for the widget class in the HTML) and queue the URL for a later attempt instead of retrying in a tight loop. Failed and unsolvable tasks are free; key or balance errors are printed by the helper and should stop the job. Turnstile tasks cost $0.84 per 1,000 and AWS WAF tasks $1.40, charged only when an answer arrives.
Scaling crawls
For many URLs, arun_many runs pages concurrently; each page that triggers the hook solves independently, and GateSolver has no cap on concurrent tasks. Watch the shared limit of 600 API requests per minute per key when many pages solve at once, and keep Crawl4AI's own concurrency modest so the target site is not flooded. Reuse a session per site so one answer serves many pages, and refresh only when the protection returns. Use the crawler for public data, monitoring and research that the site's terms allow. For background, read AI agents in web scraping.
Common questions
Does Crawl4AI solve CAPTCHAs on its own?
No. It renders pages and extracts content; the hooks shown here add solving by calling the GateSolver HTTP API.
Which hook should I use for a widget on a form?
after_goto, because the widget must exist in the loaded page before its key can be read and the token placed.
Why add the WAF cookie in on_page_context_created?
That hook runs before navigation, so the very first request to the site already carries the cookie and skips the challenge page.
Do hook signatures change between Crawl4AI versions?
They can. The examples accept extra keyword arguments to stay tolerant, but compare them with the hooks documentation for your installed release.
Can I use the LLM extraction features after solving?
Yes. Solving only changes which page is loaded; any extraction strategy in the run config then works on the real content.
Keep reading
- PlaywrightPlaywright in Node.js and Python: read widget keys from the DOM or network, inject tokens, and add answers through route interception.
- AWS WAF solver$1.40 per 1,000 tasks, answers under 3 seconds.
- How AI agents are used in web scrapingWhere language model agents genuinely help a scraper, from planning crawls to messy extraction and selector repair, and where they fall short.
- Cloudflare Turnstile solver$0.84 per 1,000 tasks, answers under 3 seconds.