Trio Async Scraping with Proxies: Structured Concurrency for Web Scraping
Introduction
In the world of web scraping and automation, using proxies effectively is crucial for maintaining anonymity, bypassing rate limits, and avoiding IP bans. Python offers several asynchronous libraries to handle these tasks efficiently, and one such library that stands out for its structured concurrency model is Trio. Unlike asyncio, which can be prone to resource leaks due to uncontrolled task lifecycles, Trio's approach using nurseries ensures that tasks are properly managed within their defined scopes.
This guide will walk you through how to use Trio along with the httpx library (which supports Trio as a backend) for asynchronous web scraping. We'll cover setting up a proxy-rotating fetcher, implementing rate limiting with trio.CapacityLimiter, and managing tasks with nurseries. This structured approach not only enhances the reliability of your scrapers but also makes them easier to debug.
Setting Up Trio and httpx
First, ensure you have Trio and httpx installed in your environment:
pip install trio httpx
Basic Asynchronous Request with Proxy
Let's start by making a basic asynchronous request using httpx with a proxy. We'll use trio.run() to execute our async function.
import trio
import httpx
async def fetch(url, proxy):
async with httpx.AsyncClient(proxies={"all": proxy}) as client:
response = await client.get(url)
print(response.status_code)
trio.run(fetch, "https://httpbin.org/ip", "http://your-proxy:port")
Using Nurseries for Concurrent Tasks
Trio's nursery pattern is a powerful tool for managing multiple tasks concurrently. Here’s how you can use it to fetch multiple URLs in parallel.
import trio
import httpx
async def fetch(url, proxy):
async with httpx.AsyncClient(proxies={"all": proxy}) as client:
response = await client.get(url)
print(f"{url}: {response.status_code}")
async def main(urls, proxies):
async with trio.open_nursery() as nursery:
for url in urls:
# Use a rotating proxy mechanism here
proxy = next(proxies)
nursery.start_soon(fetch, url, proxy)
urls = [
"https://httpbin.org/ip",
"https://jsonplaceholder.typicode.com/posts/1",
"https://api.github.com"
]
# Simple proxy rotation generator
proxies = iter([
"http://proxy1:port",
"http://proxy2:port",
"http://proxy3:port"
])
trio.run(main, urls, proxies)
Proxy Rotation and Error Handling
In a production environment, you need to handle errors gracefully and ensure that your proxy list is always up-to-date. Here’s an enhanced version with basic error handling:
import trio
import httpx
async def fetch(url, proxy):
try:
async with httpx.AsyncClient(proxies={"all": proxy}) as client:
response = await client.get(url)
print(f"{url}: {response.status_code}")
except httpx.RequestError as e:
print(f"Request failed for {url} with proxy {proxy}: {e}")
async def main(urls, proxies):
async with trio.open_nursery() as nursery:
for url in urls:
proxy = next(proxies)
nursery.start_soon(fetch, url, proxy)
urls = [
"https://httpbin.org/ip",
"https://jsonplaceholder.typicode.com/posts/1",
"https://api.github.com"
]
# Simple proxy rotation generator
proxies = iter([
"http://proxy1:port",
"http://proxy2:port",
"http://proxy3:port"
])
trio.run(main, urls, proxies)
Implementing Rate Limiting
To avoid overloading servers and getting banned, implementing rate limiting is essential. Trio's CapacityLimiter can be used to control the number of concurrent requests.
import trio
import httpx
async def fetch(url, proxy, limiter):
async with limiter:
try:
async with httpx.AsyncClient(proxies={"all": proxy}) as client:
response = await client.get(url)
print(f"{url}: {response.status_code}")
except httpx.RequestError as e:
print(f"Request failed for {url} with proxy {proxy}: {e}")
async def main(urls, proxies):
limiter = trio.CapacityLimiter(max_concurrent=5) # Limit to 5 concurrent requests
async with trio.open_nursery() as nursery:
for url in urls:
proxy = next(proxies)
nursery.start_soon(fetch, url, proxy, limiter)
urls = [
"https://httpbin.org/ip",
"https://jsonplaceholder.typicode.com/posts/1",
"https://api.github.com"
]
# Simple proxy rotation generator
proxies = iter([
"http://proxy1:port",
"http://proxy2:port",
"http://proxy3:port"
])
trio.run(main, urls, proxies)
Why Trio Over asyncio for Scraping?
- Better Cancellation: In Trio, tasks can be cancelled cleanly even on
KeyboardInterrupt. This is crucial for long-running scrapers. - Cleaner Stack Traces: Trio provides more readable stack traces, making debugging easier.
- Explicit Task Scope: Tasks are always managed within their nursery scope, preventing resource leaks.
While asyncio has a larger ecosystem and more libraries, Trio's structured concurrency model can offer better reliability and debuggability, especially in scenarios where managing resources and tasks explicitly is critical.
Best Use Case for Trio
Trio is best suited for custom proxy-rotating fetchers where reliability and debuggability are paramount. If you need a wide range of libraries or a larger ecosystem, asyncio might be more appropriate. However, for applications where you need precise control over task execution and resource management, Trio is an excellent choice.
Conclusion
Trio provides a powerful and efficient way to handle asynchronous web scraping tasks with structured concurrency. By using nurseries to manage tasks and trio.CapacityLimiter for rate limiting, you can create robust scrapers that are reliable and easy to debug. Whether you're dealing with simple proxy rotation or more complex scenarios involving multiple proxies and rate limits, Trio offers a solid foundation.
If you'd rather not manage proxy lists manually, ProxyForge auto-tests and rotates proxies locally on your machine — one-off $29 unlock, no subscription: https://proxyforge.dev/#download. This can significantly simplify the process of maintaining a reliable proxy pool for your scraping tasks.
Free proxies break. ProxyForge doesn't.
The free lists above are public and often unreliable. ProxyForge auto-tests and rotates proxies on your machine, your IP — no stale lists, no shared pools, no surprises. One-off purchase, no subscription.
Download ProxyForge free →Need guaranteed uptime? Try a premium provider