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

Web scraping

Async scraping with aiohttp

aiohttp lets one Python process wait on many pages at once. The trick is keeping that power under control: shared sessions, firm limits, sensible timeouts, and slow work such as CAPTCHA polling that never stalls the rest.

Why async for scraping

Scraping is mostly waiting. A request spends most of its life idle while the server thinks and the bytes travel. Async code uses that idle time to start other requests, so a single thread can keep dozens of transfers in flight. With aiohttp you get an async HTTP client that is mature, fast and close to the metal. What you do not get is a framework: limits, retries and scheduling are yours to design, which is what this guide covers.

One session for the whole run

Create one ClientSession and share it. Each session owns a connection pool; creating a session per request throws that pool away and opens new TCP and TLS connections every time. Configure the pool through a TCPConnector.

import aiohttp

def build_session() -> aiohttp.ClientSession:
    pool = aiohttp.TCPConnector(limit=30, limit_per_host=4, ttl_dns_cache=300)
    clock = aiohttp.ClientTimeout(total=40, sock_connect=8, sock_read=25)
    return aiohttp.ClientSession(
        connector=pool, timeout=clock,
        headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) dataset-builder/3.1",
                 "Accept-Language": "en-GB,en;q=0.7"},
    )

limit caps open connections overall and limit_per_host caps them per site, which is the number that matters for politeness. The timeout sets a ceiling for the whole request and separate ceilings for connecting and for each read, so one slow server cannot hold a slot forever.

A fetch with retries and jitter

Retry transient failures, and wait longer after each attempt. Random jitter spreads retries out so a burst of failures does not come back as a synchronized burst of retries.

import asyncio
import random

RETRYABLE = {429, 500, 502, 503, 504}

async def fetch_text(http: aiohttp.ClientSession, url: str, attempts: int = 4) -> str | None:
    for n in range(attempts):
        try:
            async with http.get(url) as r:
                if r.status in RETRYABLE:
                    ra_header = r.headers.get("Retry-After", "")
                    wait = float(ra_header) if ra_header.isdigit() else 2 ** n
                    await asyncio.sleep(wait + random.random())
                    continue
                if r.status >= 400:
                    return None
                return await r.text()
        except (aiohttp.ClientError, asyncio.TimeoutError):
            await asyncio.sleep(2 ** n + random.random())
    return None

Reading the body inside the async with block matters: once the block exits, the connection goes back to the pool and the body is no longer available. Returning None for permanent failures lets the caller count them instead of crashing the whole run.

Bounding the crawl

Launching ten thousand coroutines at once is easy and unkind. The connector limits connections, but every waiting coroutine still holds memory. A worker pool reading from a queue keeps the number of active tasks fixed and makes the crawl easy to stop.

from lxml import html as lh

async def worker(http, todo: asyncio.Queue, found: list):
    while True:
        url = await todo.get()
        try:
            body = await fetch_text(http, url)
            if body:
                tree = lh.fromstring(body)
                found.extend({"url": url, "title": t.strip()}
                             for t in tree.xpath("//h2[@class='entry-title']/a/text()"))
            await asyncio.sleep(random.uniform(0.4, 1.2))
        finally:
            todo.task_done()

async def crawl(urls: list[str], workers: int = 6) -> list:
    todo, found = asyncio.Queue(), []
    for u in urls:
        todo.put_nowait(u)
    async with build_session() as http:
        crew = [asyncio.create_task(worker(http, todo, found)) for _ in range(workers)]
        await todo.join()
        for c in crew:
            c.cancel()
        await asyncio.gather(*crew, return_exceptions=True)
    return found

Six workers means at most six requests in flight, regardless of how many URLs are queued. The small sleep after each page spreads load over time. todo.join() waits until every URL has been processed, then the workers are cancelled cleanly. This example parses with lxml and XPath; Beautiful Soup works too, but lxml is lighter when you parse many pages.

Polling a CAPTCHA task without blocking

When a page turns out to be a challenge, solving it means waiting several seconds for an answer. In async code, that wait must use await asyncio.sleep, never time.sleep, so other workers keep running. The function below reuses the same session for the API calls.

async def solve_turnstile(http, page_url: str, sitekey: str, api_key: str) -> str:
    async def api(method, data):
        async with http.post(f"https://gatesolver.com/{method}",
                             json={"clientKey": api_key, **data}) as r:
            reply = await r.json(content_type=None)
        if reply.get("errorId"):
            raise RuntimeError(reply.get("errorCode"))
        return reply
    t = await api("createTask", {"task": {"type": "AntiTurnstileTaskProxyLess",
                                          "websiteURL": page_url, "websiteKey": sitekey}})
    for _ in range(40):
        await asyncio.sleep(3)
        s = await api("getTaskResult", {"taskId": t["taskId"]})
        if s["status"] == "ready":
            return s["solution"]["token"]
        if s["status"] == "failed":
            raise RuntimeError("Turnstile task failed (free)")
    raise TimeoutError("Turnstile token not ready")

The API has no limit on concurrent tasks, so several workers can wait on solves at the same time. What does have a limit is your request rate: 600 calls per minute per key. With a three second poll interval, even twenty simultaneous solves stay at about 400 calls a minute. Remember that the per host connection limit applies to the API host as well, which is another reason to keep it modest rather than huge.

Detecting the challenge in the worker

Add a check after fetch_text: if the body contains a Turnstile widget (cf-turnstile with a data-sitekey starting with 0x4), read the key, call solve_turnstile, and post the form with the token in cf-turnstile-response. Then continue with the normal parsing. The Turnstile in Python guide shows the form submission in detail.

Respecting each site separately

A crawl that covers several sites should apply politeness per site, not globally. limit_per_host already caps connections per host, but pacing deserves the same treatment. Keep a small dictionary of the last request time per hostname and, before each fetch, sleep until a minimum gap for that host has passed. That way a fast site and a slow site can share one crawl: the fast one gets requests at its comfortable pace while the slow one is never crowded. If a host answers with 429 more than once, double its gap for the rest of the run. These few lines of bookkeeping do more to avoid blocks and challenge pages than any header trick.

Shutting down cleanly

Always close the session, ideally with async with as above. On Ctrl+C, asyncio.run cancels the main task; the finally blocks and the session's context manager release connections. If you write results incrementally to disk, flush after each batch so an interrupted run keeps what it collected.

Common mistakes

  • A session per request: slow and wasteful. Share one.
  • time.sleep in a coroutine: freezes every task. Use asyncio.sleep.
  • Unbounded gather over thousands of URLs: memory spikes and bursts of traffic. Use a worker pool.
  • Reading the body after the context closes: raises an error. Read inside async with.
Async makes it easy to send a lot of traffic very quickly. Set per host limits first, add pauses, and grow concurrency only while the site responds comfortably.

For an alternative client with HTTP/2 support see scraping with HTTPX, and for a full framework with these features built in, Scrapy. The concurrency glossary entry explains the underlying ideas.

Common questions

How many aiohttp requests should run at once?

Set limit_per_host low, often a handful per site, and raise it only while the site responds normally. The total limit can be higher if you crawl many sites.

Why create only one ClientSession?

Each session owns a connection pool. Sharing one reuses TCP and TLS connections, which is faster and lighter for the target servers.

Can I use time.sleep inside async code?

No. It blocks the event loop and every other task. Use await asyncio.sleep instead.

How do I poll a CAPTCHA task in aiohttp?

Create the task, then loop with await asyncio.sleep of three seconds between getTaskResult calls, so other coroutines keep running.

Is aiohttp faster than requests?

For many URLs, yes, because it overlaps waiting time. For a single request the difference is negligible.

Keep reading