ProxyForge Download

Async Python Scraping with Rotating Proxies: aiohttp + asyncio at Scale

Async Python Scraping with Rotating Proxies: aiohttp + asyncio at Scale

When it comes to web scraping at scale, you need tools that can handle multiple requests concurrently while adhering to site policies and avoiding IP bans. In this guide, we'll explore how to build a production-grade async scraper using aiohttp for HTTP requests and asyncio for managing asynchronous tasks. We'll also cover strategies for rotating proxies, implementing rate limiting with asyncio.Semaphore, handling common errors like 407 Proxy Authentication Required and 429 Too Many Requests with exponential backoff, and determining when to upgrade from free to paid residential proxies.

Introduction

Web scraping at scale requires efficient handling of multiple requests. Traditional synchronous approaches can be slow and inefficient, especially when dealing with sites that impose strict rate limits or require proxy rotation to avoid IP bans. This guide will walk you through building an async scraper using Python's aiohttp library for HTTP requests and asyncio for managing asynchronous tasks.

Setting Up the Environment

Before we dive into the code, ensure you have the necessary libraries installed:

pip install aiohttp asyncio

For proxy rotation, you might also need a list of proxies. You can use free proxy lists or paid services like Bright Data or SmartProxy. For this guide, let's assume you have a list of proxies stored in a file called proxies.txt.

Building the Async Scraper

1. Proxy Rotation with aiohttp.ClientSession

We'll start by setting up an aiohttp.ClientSession to handle HTTP requests and rotate proxies. Here’s a basic setup:

import asyncio
import aiohttp
from random import choice

async def fetch(session, url):
    proxy = choice(proxies)
    try:
        async with session.get(url, proxy=proxy) as response:
            return await response.text()
    except (aiohttp.ClientError, asyncio.TimeoutError) as e:
        print(f"Request failed: {e}")

async def main(urls):
    async with aiohttp.ClientSession() as session:
        tasks = [fetch(session, url) for url in urls]
        results = await asyncio.gather(*tasks)
        return results

# Example usage
urls = ["https://example.com", "https://example.org"]
proxies = open('proxies.txt').read().splitlines()
asyncio.run(main(urls))

2. Rate Limiting with asyncio.Semaphore

To prevent overwhelming the target server, we can use asyncio.Semaphore to limit the number of concurrent requests:

import asyncio
import aiohttp
from random import choice

MAX_CONCURRENT_REQUESTS = 10
semaphore = asyncio.Semaphore(MAX_CONCURRENT_REQUESTS)

async def fetch(session, url):
    async with semaphore:
        proxy = choice(proxies)
        try:
            async with session.get(url, proxy=proxy) as response:
                return await response.text()
        except (aiohttp.ClientError, asyncio.TimeoutError) as e:
            print(f"Request failed: {e}")

async def main(urls):
    async with aiohttp.ClientSession() as session:
        tasks = [fetch(session, url) for url in urls]
        results = await asyncio.gather(*tasks)
        return results

# Example usage
urls = ["https://example.com", "https://example.org"]
proxies = open('proxies.txt').read().splitlines()
asyncio.run(main(urls))

3. Handling Common Errors with Exponential Backoff

To handle errors like 407 Proxy Authentication Required and 429 Too Many Requests, we can implement exponential backoff:

import asyncio
import aiohttp
from random import choice
import time

MAX_CONCURRENT_REQUESTS = 10
semaphore = asyncio.Semaphore(MAX_CONCURRENT_REQUESTS)
BACKOFF_FACTOR = 0.3
MAX_BACKOFF_SECONDS = 60

async def fetch(session, url):
    async with semaphore:
        proxy = choice(proxies)
        try:
            async with session.get(url, proxy=proxy) as response:
                if response.status == 429:
                    backoff_time = min((BACKOFF_FACTOR * (2 ** response.history.count())), MAX_BACKOFF_SECONDS)
                    print(f"Too Many Requests. Retrying after {backoff_time} seconds...")
                    await asyncio.sleep(backoff_time)
                    return await fetch(session, url)  # Retry the request
                return await response.text()
        except (aiohttp.ClientError, asyncio.TimeoutError) as e:
            if isinstance(e, aiohttp.ClientResponseError) and e.status == 407:
                backoff_time = min((BACKOFF_FACTOR * (2 ** len(proxies))), MAX_BACKOFF_SECONDS)
                print(f"Proxy Authentication Required. Retrying after {backoff_time} seconds...")
                await asyncio.sleep(backoff_time)
                return await fetch(session, url)  # Retry the request
            print(f"Request failed: {e}")

async def main(urls):
    async with aiohttp.ClientSession() as session:
        tasks = [fetch(session, url) for url in urls]
        results = await asyncio.gather(*tasks)
        return results

# Example usage
urls = ["https://example.com", "https://example.org"]
proxies = open('proxies.txt').read().splitlines()
asyncio.run(main(urls))

When to Upgrade from Free to Paid Residential Proxies

Free proxies are often unreliable and can lead to IP bans or poor performance. They may also have low speeds and limited anonymity, making them unsuitable for production-grade scraping at scale.

When you reach around 10k+ requests per day, consider upgrading to paid residential proxies like Bright Data or SmartProxy. These services offer:

Conclusion

Building a production-grade async scraper with aiohttp and asyncio is a powerful way to handle large-scale web scraping tasks. By implementing proxy rotation, rate limiting, and error handling strategies like exponential backoff, you can efficiently scrape data while adhering to site policies and avoiding IP bans.

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

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 →