Async Web Scraping in Python With HTTPX and asyncio (2026)

Build a fast async scraper in Python with HTTPX and asyncio: semaphores, retries with backoff, per-host limits and proxies, plus a real sync vs async benchmark.

Author
ProxyHorizon Team
Published
November 28, 2026
15 min read
Expert-Verified
Async Web Scraping in Python With HTTPX and asyncio (2026)

A normal Python scraper spends most of its life waiting. It sends a request, sits idle while the server responds, parses the page, then sends the next one. With 50 pages and a server that takes most of a second to answer, that idle time adds up fast.

Async scraping fixes that. Instead of waiting for each response in turn, your scraper sends many requests at once and handles each reply as it arrives. In our test, the same 50-page job dropped from 36.1 seconds to 4.8 seconds.

This guide builds an async scraper step by step with HTTPX and asyncio. You’ll add concurrency limits, retries with backoff, per-host limits and proxy support, then see the benchmark against a regular synchronous version. Every piece of code here was run, and the output is real.

TL;DR
  • Async overlaps network waiting, so many requests run at once on one thread.
  • Our 50-page test: 36.1s with requests, 4.8s with async HTTPX at concurrency 10.
  • Use a semaphore, per-host limits and one shared AsyncClient.
  • Retry 429 and 5xx with exponential backoff and jitter, not 403 or 404.
  • HTTPX 0.28 uses proxy=, not proxies=, for proxy support.

Why Async Scraping Is So Much Faster

Scraping is I/O-bound: the slow part is waiting on the network, not running your code. Async lets one program wait on many requests at the same time.

In a synchronous scraper, each requests.get() call blocks. Your program does nothing until the response comes back. If a page takes 700 milliseconds, 50 pages take about 35 seconds, even though your CPU was idle for nearly all of it.

Async code runs on an event loop. When a request is sent, the coroutine hands control back to the loop with await, and the loop starts the next request. When any response arrives, the loop picks up the coroutine that was waiting for it. Many requests overlap in time, on a single thread.

Timeline comparing synchronous scraping, where requests run one after another, with async scraping, where many requests overlap
Sync scraping waits for each response in turn. Async overlaps the waiting, so total time shrinks.

That’s also the limit of async. It speeds up waiting, not computing. If your scraper spends most of its time parsing huge pages or running heavy processing, async alone won’t help much. We cover how to handle that later.

Async vs Threads vs Multiprocessing

Python has three ways to do more than one thing at once. For fetching web pages, async is usually the best fit.

asyncioThreadsMultiprocessing
Best forMany network requestsNetwork requests with blocking librariesCPU-heavy work like parsing or ML
Overhead per taskVery lowModerateHigh
Practical scaleHundreds to thousands of requests in flightTens to low hundreds of threadsRoughly one process per CPU core
Library needsAsync libraries like HTTPX or aiohttpWorks with requestsWorks with anything
Main riskOne blocking call stalls everythingShared-state bugsMemory use, slow startup

Threads with requests and a ThreadPoolExecutor are a fine choice for small jobs. Async pulls ahead when you need hundreds of requests in flight, fine control over rate limits, or a scraper that shares one connection pool efficiently.

What You Need

You need Python 3.9 or newer, HTTPX and Beautiful Soup. We ran everything on Python 3.13 with HTTPX 0.28.1.

Bash
pip install httpx beautifulsoup4

HTTPX gives you an API that feels like requests, with both a sync and an async client. That makes it easy to move existing code over. If you’re new to scraping in Python, start with our Python web scraping guide first.

All the examples scrape Books to Scrape, a public practice site with 1,000 books spread across 50 listing pages.

Step 1: The Synchronous Baseline

Start with a plain sync scraper, so you have something to measure against. This one uses a requests.Session to fetch all 50 listing pages in order and pull the title and price of each book.

Python
import time
import requests
from bs4 import BeautifulSoup

BASE = "https://books.toscrape.com/catalogue/page-{}.html"

def parse(html):
    soup = BeautifulSoup(html, "html.parser")
    return [{"title": b.h3.a["title"], "price": b.select_one(".price_color").text}
            for b in soup.select("article.product_pod")]

start = time.perf_counter()
books = []
with requests.Session() as s:
    for n in range(1, 51):
        r = s.get(BASE.format(n), timeout=20)
        r.raise_for_status()
        books += parse(r.content)
print(f"sync: {len(books)} books from 50 pages in {time.perf_counter() - start:.1f}s")

It worked, and it was slow: 1,000 books from 50 pages in 36.1 seconds, about 0.7 seconds per page. Almost all of that was waiting for the server.

Note that we pass r.content, the raw bytes, to Beautiful Soup. This site sends Content-Type: text/html with no character set, so requests falls back to ISO-8859-1 and r.text turns “£51.77” into “£51.77”. Passing bytes lets Beautiful Soup read the page’s own encoding.

Step 2: Your First Async Requests With HTTPX

Three changes turn sync code into async code: an async def function, an AsyncClient, and await on each request.

Python
import asyncio
import httpx

async def main():
    urls = [f"https://books.toscrape.com/catalogue/page-{n}.html" for n in range(1, 6)]
    async with httpx.AsyncClient(timeout=20) as client:
        responses = await asyncio.gather(*(client.get(u) for u in urls))
    for r in responses:
        print(r.status_code, r.url, len(r.content), "bytes")

asyncio.run(main())

All five pages came back with status 200, fetched at the same time. Here’s what each part does:

  • async with httpx.AsyncClient() opens one client with a shared connection pool, and closes it cleanly at the end.
  • client.get(u) without await creates a coroutine, a request that hasn’t started yet.
  • asyncio.gather() runs all of them concurrently and returns the results in the same order as the input.
  • asyncio.run(main()) starts the event loop and runs until main() finishes.

Set a timeout explicitly. HTTPX defaults to five seconds, which is short for slow sites, and a hung request with no timeout can stall a whole batch.

Step 3: Limit Concurrency With a Semaphore

Firing every request at once works for five pages. For 5,000, it will overload the site, get you blocked and possibly crash your scraper.

An asyncio.Semaphore is a counter that only lets a fixed number of tasks through at a time. Wrap each request in async with semaphore:, and only that many requests are ever in flight. The rest wait their turn, without blocking the event loop.

HTTPX also has its own connection limit. By default, an AsyncClient allows up to 100 connections and keeps 20 alive for reuse. Set httpx.Limits to match your semaphore, so the pool and your concurrency agree.

How high should you go? Our benchmark below shows the pattern: big gains from 1 to 10 concurrent requests, then very little extra from 10 to 20. Past that point, you’re mostly adding load on the site. Start around 5 to 10 per website and raise it only if the site handles it without errors or slowdowns.

Step 4: Add Retries With Exponential Backoff

At any real scale, some requests fail. A good async scraper retries the temporary failures and gives up cleanly on the rest.

Retry these, because they usually clear up on their own:

  • 429 Too Many Requests, which means you’re going too fast. Honor the Retry-After header if the server sends one.
  • 500, 502, 503 and 504 server and gateway errors.
  • Timeouts and connection errors, such as a dropped connection or a slow proxy.

Don’t retry 403 or 404. A 403 usually means you’re blocked, and hammering the site again makes it worse. A 404 means the page doesn’t exist.

Wait longer after each failure. Exponential backoff doubles the delay each time: 1 second, then 2, then 4. Add a little random jitter so that dozens of failed tasks don’t all retry at the same instant.

We tested the retry logic against a small local server that deliberately fails each page twice, first with a 429 and a one-second Retry-After, then with a 503. The scraper waited 1 second after the 429, about 2 seconds after the 503, then got the page on the third try. Both test pages came back correctly.

One important detail: release the semaphore before sleeping. In the full scraper below, the async with block only wraps the request itself. A task waiting to retry doesn’t hold a slot that another request could be using.

Step 5: Per-Host Limits and Connection Reuse

If you scrape several websites in one run, a single global limit isn’t enough. Each site needs its own cap.

Imagine a global limit of 20 and a job split between two sites. Without per-host limits, all 20 slots could land on one small site. The fix is a dictionary of semaphores keyed by hostname. A request has to get through both the global semaphore and its host’s semaphore before it runs.

Reusing one client matters as much as limiting it. Creating a new AsyncClient for each request throws away the connection pool, so every request pays for a new TCP connection and TLS handshake. Create one client per job, share it across tasks, and close it at the end.

Step 6: Route Requests Through Proxies

Fast scrapers attract rate limits and blocks. Proxies spread your requests across many IP addresses, and HTTPX makes adding one a single argument.

Pass the proxy URL to the client with proxy=, including credentials if your provider uses them, such as http://user:pass@gate.example.com:7000. Note that HTTPX 0.28 removed the older proxies= argument, so code from older tutorials will fail with a TypeError. For different proxies per scheme or per domain, use mounts=.

We tested the full scraper through a small local CONNECT proxy. All 50 pages came back with 1,000 books in 5.5 seconds. The proxy’s log showed just 10 CONNECT tunnels to books.toscrape.com:443 for 50 requests. HTTPX’s pool reused each tunnel for several requests.

That reuse matters if you need a new IP for each request. With a rotating proxy gateway, a reused connection usually keeps the same exit IP.

If you need rotation per request, check whether your provider rotates on each new connection or offers a session parameter, or create one client per proxy. Our guides to proxies with Python Requests and building a rotating proxy script cover the patterns, and the proxy provider directory compares rotating options.

The Complete Async Scraper

Here’s everything combined: a global semaphore, per-host semaphores, retries with backoff and jitter, optional proxy support and CSV output.

Python
import asyncio, csv, random, sys, time
from collections import defaultdict
from urllib.parse import urlsplit
import httpx
from bs4 import BeautifulSoup

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

class AsyncScraper:
    def __init__(self, concurrency=10, per_host=5, retries=3, proxy=None):
        self.global_limit = asyncio.Semaphore(concurrency)          # total requests in flight
        self.host_limits = defaultdict(lambda: asyncio.Semaphore(per_host))  # per website
        self.retries = retries
        self.client = httpx.AsyncClient(
            proxy=proxy,                                              # e.g. "http://user:pass@host:port"
            timeout=httpx.Timeout(20.0, connect=10.0),
            limits=httpx.Limits(max_connections=concurrency, max_keepalive_connections=concurrency),
            headers={"User-Agent": "Mozilla/5.0 (compatible; async-scraper-demo/1.0)"},
            follow_redirects=True,
        )

    async def fetch(self, url):
        host = urlsplit(url).hostname
        for attempt in range(self.retries + 1):
            try:
                async with self.global_limit, self.host_limits[host]:
                    r = await self.client.get(url)
                if r.status_code not in RETRY_STATUS:
                    r.raise_for_status()
                    return r.content
                wait = float(r.headers.get("Retry-After", 2 ** attempt))
                reason = r.status_code
            except (httpx.TimeoutException, httpx.TransportError) as e:
                wait, reason = 2 ** attempt, type(e).__name__
            if attempt == self.retries:
                raise RuntimeError(f"gave up on {url} after {reason}")
            wait += random.uniform(0, 0.5)                            # jitter
            print(f"  retry {attempt + 1} for {url} after {reason}, sleeping {wait:.1f}s")
            await asyncio.sleep(wait)

    async def close(self):
        await self.client.aclose()

def parse(html):
    soup = BeautifulSoup(html, "html.parser")
    return [{"title": b.h3.a["title"], "price": b.select_one(".price_color").text}
            for b in soup.select("article.product_pod")]

async def main(concurrency=10, proxy=None):
    urls = [f"https://books.toscrape.com/catalogue/page-{n}.html" for n in range(1, 51)]
    scraper = AsyncScraper(concurrency=concurrency, per_host=concurrency, proxy=proxy)
    start = time.perf_counter()
    try:
        pages = await asyncio.gather(*(scraper.fetch(u) for u in urls), return_exceptions=True)
    finally:
        await scraper.close()
    books, failed = [], 0
    for page in pages:
        if isinstance(page, Exception):
            failed += 1
            continue
        books += parse(page)
    print(f"async (concurrency={concurrency}): {len(books)} books, {failed} failed, "
          f"{time.perf_counter() - start:.1f}s")
    with open("books.csv", "w", newline="", encoding="utf-8") as f:
        w = csv.DictWriter(f, fieldnames=["title", "price"])
        w.writeheader(); w.writerows(books)

if __name__ == "__main__":
    asyncio.run(main(int(sys.argv[1]) if len(sys.argv) > 1 else 10,
                     sys.argv[2] if len(sys.argv) > 2 else None))

Run it with a concurrency level and an optional proxy, for example python async_scraper.py 10 or python async_scraper.py 10 http://user:pass@host:port. It writes the results to books.csv.

Two details are worth copying into your own scrapers. asyncio.gather(..., return_exceptions=True) means one failed page doesn’t cancel the rest; failures come back as exception objects that you can count and log. And the try/finally makes sure the client closes even if something goes wrong.

Scaling Up: A Queue With Worker Tasks

Gathering a list of URLs works when you know them all up front. When pages lead to more pages, use a queue and a fixed pool of workers.

This pattern is how most real crawlers work. You put starting URLs in an asyncio.Queue, start a fixed number of worker tasks, and each worker loops: take a URL, fetch it, and either extract data or add new URLs to the queue. The number of workers is your concurrency limit, so you don’t need a separate semaphore.

Python
import asyncio, time
from urllib.parse import urljoin
import httpx
from bs4 import BeautifulSoup

START = "https://books.toscrape.com/catalogue/page-{}.html"
WORKERS = 8

async def worker(name, client, queue, results):
    while True:
        url = await queue.get()
        try:
            r = await client.get(url)
            soup = BeautifulSoup(r.content, "html.parser")
            if "/page-" in url:                      # listing page: queue every book on it
                for a in soup.select("article.product_pod h3 a"):
                    await queue.put(urljoin(url, a["href"]))
            else:                                    # book page: extract details
                results.append({
                    "title": soup.h1.text,
                    "price": soup.select_one(".price_color").text,
                    "stock": soup.select_one(".availability").text.split("(")[1].split()[0],
                })
        except Exception as e:
            print(f"{name} failed on {url}: {e!r}")
        finally:
            queue.task_done()

async def main(pages=5):
    queue, results = asyncio.Queue(), []
    for n in range(1, pages + 1):
        queue.put_nowait(START.format(n))
    start = time.perf_counter()
    async with httpx.AsyncClient(timeout=20, limits=httpx.Limits(max_connections=WORKERS)) as client:
        workers = [asyncio.create_task(worker(f"w{i}", client, queue, results)) for i in range(WORKERS)]
        await queue.join()                           # wait until every queued URL is processed
        for w in workers:
            w.cancel()
    print(f"{WORKERS} workers scraped {len(results)} book pages in {time.perf_counter() - start:.1f}s")
    print("example:", results[0])

asyncio.run(main())

We seeded the queue with the first five listing pages. The workers found 100 book links on them, queued each one, then pulled the title, price and stock count from every book page. Eight workers finished all 105 requests in 10.9 seconds.

The queue also solves the memory problem with huge jobs. Instead of creating a million coroutines at once, you only ever have as many running as you have workers. queue.join() waits until every queued item has been marked done, then the workers are cancelled.

Optional: Turn On HTTP/2

HTTPX can speak HTTP/2, which sends many requests over a single connection to the same site. Install the extra with pip install "httpx[http2]" and create the client with httpx.AsyncClient(http2=True).

It only helps when the server supports HTTP/2, and gains vary. Test it on your target before relying on it. Some anti-bot systems also look at HTTP/2 settings as part of a client fingerprint, so a change of protocol can change how a site treats you.

Benchmark: Sync vs Async

We timed the same job, fetching and parsing all 50 listing pages, with the sync scraper and with the async scraper at four concurrency levels.

VersionBooksFailed pagesTimeSpeed-up
Sync (requests)1,000036.1s1x
Async, concurrency 11,000034.5s1.0x
Async, concurrency 51,00008.9s4.1x
Async, concurrency 101,00004.8s7.5x
Async, concurrency 201,00004.1s8.8x

The pattern is the useful part. At concurrency 1, async is no faster than sync, which proves the speed comes from overlap, not from HTTPX itself. Going from 1 to 10 cut the time by about 86%. Doubling again to 20 saved only another 0.7 seconds.

These are single runs from our test machine against one practice site, so treat the exact numbers as an example. Your results depend on the site’s response time, your network and how much parsing each page needs.

Terminal output of the sync vs async scraping benchmark, retry test and proxy test, showing 36.1 seconds sync versus 4.8 seconds async at concurrency 10
Real output from our runs: the benchmark, the retry test against a failing server, and the proxied run.
Diagram of the building blocks of a production async scraper: shared client, semaphore, per-host limits, retries with backoff, and proxies
The five building blocks that turn a fast async script into a reliable scraper.

Common Async Scraping Mistakes

Most async scrapers that turn out slow or flaky make one of these mistakes.

  • Calling blocking code inside async functions. requests.get() or time.sleep() inside a coroutine freezes the whole event loop. Use await client.get() and await asyncio.sleep().
  • Heavy parsing on the event loop. Parsing is CPU work, and it blocks other tasks while it runs. For big pages, move it off the loop with await asyncio.to_thread(parse, html), or use a faster parser like lxml.
  • No concurrency limit. Gathering 10,000 requests with no semaphore opens far too many connections and gets you blocked.
  • One client per request. It throws away connection reuse and adds a TLS handshake to every page.
  • Forgetting return_exceptions=True. Without it, the first failure raises out of gather() and you lose track of the remaining tasks’ results.
  • Building a list of 1,000,000 coroutines. For very large jobs, use a queue with a fixed number of worker tasks instead of creating everything up front.

Scrape Fast, but Scrape Politely

Async makes it easy to send more requests than a site can handle. That hurts the site and gets your scraper blocked.

Keep per-site concurrency modest, respect Retry-After, and slow down when errors rise. Our guide to rate limiting in web scraping covers token buckets and adaptive delays you can add to the scraper above.

Check the site’s terms and robots.txt before you scale up, and avoid collecting personal data you don’t need. Our guide to web scraping legality and robots.txt covers the rules in more detail.

When Async HTTPX Isn’t the Right Tool

Async HTTPX is ideal for HTML and JSON you can fetch directly. Some jobs need something else.

  • JavaScript-rendered pages. If the data only appears after scripts run, HTTPX won’t see it. Use Playwright’s async API instead. Our guide to scraping JavaScript websites shows how, and our Playwright scraping guide covers the setup.
  • Large, long-running crawls. Scrapy is built on an async engine and adds scheduling, deduplication and pipelines. It’s often a better base than a hand-written scraper past a few hundred thousand pages.
  • Distributed jobs. When one machine isn’t enough, you need a queue and multiple workers. Our article on web scraping at large scale covers that architecture.

Frequently Asked Questions

Final Thoughts

Async scraping in Python is mostly about removing idle time. HTTPX and asyncio let one process keep many requests in flight, and in our test that turned a 36-second job into a 5-second one.

Speed is only half of it. A semaphore keeps you polite, per-host limits keep one site from being swamped, retries with backoff absorb temporary failures, and a proxy setting spreads the load. Start with the complete scraper above, keep concurrency modest, and raise it only when the site and your error rate say it’s safe.