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

Web scraping

Scraping with HTTPX

HTTPX looks like requests but adds HTTP/2, a matching async client and finer control over timeouts and pools. Those features map directly onto everyday scraping problems.

Why HTTPX for scraping

HTTPX keeps the requests style API that most Python developers know, so get, post, params, headers and json() all behave as expected. On top of that it brings four features that matter for scrapers: optional HTTP/2, a synchronous Client and an AsyncClient with the same interface, timeouts that can be set per phase, and explicit connection pool limits. It also makes a few safer default choices, which can surprise people coming from requests.

Install

pip install "httpx[http2]"

The http2 extra pulls in the h2 package. Without it HTTPX speaks HTTP/1.1 only, even if you ask for HTTP/2.

A configured client

import httpx

edge = httpx.Client(
    http2=True,
    follow_redirects=True,
    timeout=httpx.Timeout(connect=5.0, read=20.0, write=10.0, pool=5.0),
    limits=httpx.Limits(max_connections=10, max_keepalive_connections=5),
    headers={"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_4) catalog-audit/0.7",
             "Accept-Language": "en-CA,en;q=0.8"},
)
first = edge.get("https://news.example.org/sections/tech")
print(first.http_version, first.status_code, first.url)

Two defaults deserve attention. HTTPX does not follow redirects unless you set follow_redirects=True, unlike requests. And it applies a default timeout of five seconds to every phase, which is safer than requests' "wait forever" but may be too short for slow pages. Setting both explicitly avoids surprises.

Timeouts by phase

The four timeout values answer different questions. connect: how long to wait for a TCP and TLS handshake. read: how long to wait between chunks of the response. write: how long to wait while sending the request body. pool: how long to wait for a free connection from your own pool. A short connect timeout fails fast on dead hosts, a longer read timeout tolerates slow page generation, and the pool timeout tells you when your own concurrency is the bottleneck. When it fires, httpx.PoolTimeout is raised, which is a clear signal to raise limits or lower concurrency.

HTTP/2 in practice

With HTTP/2 enabled, many requests to the same host share one connection and run in parallel over it. For scrapers that fetch many pages from one site, that means fewer handshakes and a traffic pattern closer to a modern browser's. Check response.http_version to see what was negotiated: servers that do not support HTTP/2 fall back to HTTP/1.1 silently.

HTTP/2 is not a disguise, though. Clients can be told apart by their HTTP/2 settings and frame order, as explained in HTTP/2 fingerprinting. HTTPX's HTTP/2 looks like HTTPX, not like Chrome. If a site insists on a browser fingerprint, see curl_cffi for browser-like requests.

Event hooks for logging and checks

Event hooks run on every request or response. They are a tidy place for logging, metrics and turning error statuses into exceptions, so the rest of your code only deals with good responses.

import logging
log = logging.getLogger("scrape")

def note_request(req: httpx.Request) -> None:
    log.info("GET %s", req.url)

def check_response(resp: httpx.Response) -> None:
    log.info("%s %s %s", resp.status_code, resp.http_version, resp.url)
    if resp.status_code in (403, 429) or resp.status_code >= 500:
        resp.read()
        resp.raise_for_status()

edge = httpx.Client(http2=True, follow_redirects=True,
                    event_hooks={"request": [note_request], "response": [check_response]})

Response hooks run before the body is read, so call resp.read() first if you want the body available in the exception for later inspection. For an AsyncClient, hooks must be async def functions and use await resp.aread().

Retries

HTTPX's transport can retry failed connection attempts: httpx.HTTPTransport(retries=2). It does not retry on status codes such as 429 or 503; that policy belongs in your code, where you can honor Retry-After and back off. A small loop around client.get that catches httpx.HTTPStatusError and httpx.TransportError covers most needs; see exponential backoff for sensible wait times.

Going async with the same code

Moving from Client to AsyncClient is mostly a matter of adding await. That makes it easy to prototype synchronously and switch when the URL list grows.

import asyncio

async def harvest(urls: list[str]) -> dict[str, int]:
    limiter = asyncio.Semaphore(8)
    async with httpx.AsyncClient(http2=True, follow_redirects=True,
                                 timeout=httpx.Timeout(15.0, connect=5.0)) as hub:
        async def grab(u: str) -> tuple[str, int]:
            async with limiter:
                r = await hub.get(u)
                return u, len(r.content)
        pairs = await asyncio.gather(*(grab(u) for u in urls))
    return dict(pairs)

sizes = asyncio.run(harvest([f"https://news.example.org/sections/tech?p={i}" for i in range(1, 11)]))

httpx.Timeout(15.0, connect=5.0) is the short form: 15 seconds for every phase except connect. With HTTP/2 on, the eight concurrent requests often travel over a single connection to the site.

Cookies and sessions

An HTTPX client keeps a cookie jar for its lifetime, just like a requests session, so a cookie set by one response is sent with the next request to the same site. You can read it as client.cookies, set values with client.cookies.set(name, value, domain=...), or start a client with cookies from elsewhere, such as a browser session you exported. Use one client per logical visitor. If you crawl several unrelated sites, separate clients keep their cookies, connection pools and HTTP/2 connections apart, which also makes logs easier to read. For long runs, recreate a client every few thousand requests or when a site starts misbehaving, so stale connections and cookies are dropped together.

Calling a CAPTCHA API with HTTPX

HTTPX's base_url option makes API clients neat. When a page in your crawl shows a challenge, a few lines turn it into an answer:

import time

solver = httpx.Client(base_url="https://gatesolver.com", timeout=httpx.Timeout(30.0))

def recaptcha_token(page: str, sitekey: str, key: str = "YOUR_API_KEY") -> str:
    made = solver.post("/createTask", json={"clientKey": key, "task": {
        "type": "ReCaptchaV2TaskProxyLess", "websiteURL": page, "websiteKey": sitekey}}).json()
    if made.get("errorId"):
        raise RuntimeError(f"createTask error {made['errorCode']}")
    while True:
        time.sleep(3)
        poll = solver.post("/getTaskResult", json={"taskId": made["taskId"], "clientKey": key})
        state = poll.json()
        if state.get("status") == "ready":
            return state["solution"].get("gRecaptchaResponse", "")
        if state.get("errorId") or state.get("status") == "failed":
            raise RuntimeError(state.get("errorCode", "failed"))

Keep the solver client separate from the scraping client so their timeouts, headers and HTTP/2 settings do not interfere. The loop ends on its own: the API marks a task as failed after 120 seconds without an answer, and failed tasks are free. The reCAPTCHA v2 Python guide shows how to submit the token.

Troubleshooting

  • Redirect responses instead of pages: set follow_redirects=True.
  • Frequent ReadTimeout: the five second default is too short for the site. Raise the read timeout.
  • PoolTimeout under load: more concurrent requests than max_connections. Raise the limit or lower concurrency.
  • http_version stays HTTP/1.1: the h2 package is missing or the server does not offer HTTP/2.
HTTP/2's multiplexing is efficient for you and for the server, but it does not change what is polite. Keep the number of concurrent requests per site low whichever protocol you use.

Common questions

Does HTTPX follow redirects by default?

No. Unlike requests, HTTPX returns the redirect response unless you set follow_redirects=True on the client or the request.

How do I enable HTTP/2 in HTTPX?

Install httpx with the http2 extra and create the client with http2=True. Check response.http_version to confirm it was negotiated.

What is the default timeout in HTTPX?

Five seconds for each phase. Set an explicit httpx.Timeout for scraping, usually with a longer read timeout.

Does HTTPX retry on 429 or 503?

No. Transport retries cover connection failures only. Handle status based retries and Retry-After in your own code.

Can I share one AsyncClient across tasks?

Yes, and you should. One client reuses its connection pool and, with HTTP/2, can multiplex many requests over one connection.

Keep reading