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.

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.
- 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.
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.
| asyncio | Threads | Multiprocessing | |
|---|---|---|---|
| Best for | Many network requests | Network requests with blocking libraries | CPU-heavy work like parsing or ML |
| Overhead per task | Very low | Moderate | High |
| Practical scale | Hundreds to thousands of requests in flight | Tens to low hundreds of threads | Roughly one process per CPU core |
| Library needs | Async libraries like HTTPX or aiohttp | Works with requests | Works with anything |
| Main risk | One blocking call stalls everything | Shared-state bugs | Memory 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.
pip install httpx beautifulsoup4HTTPX 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.
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.
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)withoutawaitcreates 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 untilmain()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-Afterheader 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.
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.
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.
| Version | Books | Failed pages | Time | Speed-up |
|---|---|---|---|---|
| Sync (requests) | 1,000 | 0 | 36.1s | 1x |
| Async, concurrency 1 | 1,000 | 0 | 34.5s | 1.0x |
| Async, concurrency 5 | 1,000 | 0 | 8.9s | 4.1x |
| Async, concurrency 10 | 1,000 | 0 | 4.8s | 7.5x |
| Async, concurrency 20 | 1,000 | 0 | 4.1s | 8.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.
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()ortime.sleep()inside a coroutine freezes the whole event loop. Useawait client.get()andawait 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 ofgather()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.
Keep Reading
More articles you might enjoy


