aiohttp Proxy Rotation in Python: Async Scraping Without Bans
Introduction
Web scraping and automation tasks often require the use of proxies to avoid being banned by target websites. In Python, aiohttp is a powerful library for asynchronous HTTP requests, making it ideal for these types of tasks. This guide will walk you through setting up proxy rotation with aiohttp, focusing on async-first principles using aiohttp.ClientSession and asyncio.gather.
We'll cover:
- Setting up basic aiohttp sessions
- Configuring aiohttp to use proxies
- Implementing a simple proxy rotation system
- Adding error handling for robustness
- Testing the setup with real requests
Basic Setup with aiohttp
Before diving into proxy rotation, let's set up a basic aiohttp session and make a request. This will serve as our foundation.
import aiohttp
import asyncio
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
urls = ['https://example.com', 'https://example.org']
async with aiohttp.ClientSession() as session:
tasks = [fetch(session, url) for url in urls]
results = await asyncio.gather(*tasks)
for result in results:
print(result)
if __name__ == '__main__':
asyncio.run(main())
This script creates an aiohttp.ClientSession, makes requests to a list of URLs concurrently, and prints the responses.
Configuring aiohttp with Proxies
To use proxies with aiohttp, you can pass a proxy parameter when creating a session. Let's modify our previous example to include a proxy:
async def fetch_with_proxy(session, url, proxy):
async with session.get(url, proxy=proxy) as response:
return await response.text()
async def main():
urls = ['https://example.com', 'https://example.org']
proxies = [
'http://yourfirstproxy:port',
'http://yoursecondproxy:port'
]
async with aiohttp.ClientSession() as session:
tasks = [fetch_with_proxy(session, url, proxies[0]) for url in urls]
results = await asyncio.gather(*tasks)
for result in results:
print(result)
if __name__ == '__main__':
asyncio.run(main())
Here, we're using the same list of URLs but passing a proxy to each request.
Implementing Proxy Rotation
To implement proxy rotation, you can cycle through your proxies within the task creation loop. This ensures that each request uses a different proxy.
async def main():
urls = ['https://example.com', 'https://example.org']
proxies = [
'http://yourfirstproxy:port',
'http://yoursecondproxy:port'
]
async with aiohttp.ClientSession() as session:
tasks = []
for i, url in enumerate(urls):
proxy_index = i % len(proxies) # Cycle through proxies
task = fetch_with_proxy(session, url, proxies[proxy_index])
tasks.append(task)
results = await asyncio.gather(*tasks)
for result in results:
print(result)
if __name__ == '__main__':
asyncio.run(main())
In this example, we cycle through the proxies list using the modulo operator to ensure that each request uses a different proxy.
Adding Error Handling
Error handling is crucial when dealing with external requests. We can add try-except blocks within our fetch function to handle exceptions like connection errors or timeouts.
async def fetch_with_proxy(session, url, proxy):
try:
async with session.get(url, proxy=proxy) as response:
if response.status == 200:
return await response.text()
else:
raise Exception(f'Failed to fetch {url} with status code {response.status}')
except aiohttp.ClientError as e:
print(f'Client error for {url}: {e}')
return None
async def main():
urls = ['https://example.com', 'https://example.org']
proxies = [
'http://yourfirstproxy:port',
'http://yoursecondproxy:port'
]
async with aiohttp.ClientSession() as session:
tasks = []
for i, url in enumerate(urls):
proxy_index = i % len(proxies)
task = fetch_with_proxy(session, url, proxies[proxy_index])
tasks.append(task)
results = await asyncio.gather(*tasks)
for result in results:
if result:
print(result)
if __name__ == '__main__':
asyncio.run(main())
Here, we handle both HTTP errors and client-side errors, printing an error message and returning None if a request fails.
Testing the Setup
To test our proxy rotation setup, you can use real URLs that require proxies to access. Make sure your proxies are working and have appropriate permissions for accessing these sites.
urls = [
'http://ipinfo.io/json', # Example URL that returns IP info
'http://httpbin.org/ip' # Another example URL that returns IP info
]
Run the script and check the output to ensure that each request is being made through a different proxy.
Conclusion
Using aiohttp for asynchronous HTTP requests with proxy rotation is an effective way to scrape websites without getting banned. By following this guide, you've learned how to set up basic sessions, configure proxies, implement proxy rotation, and add error handling.
Remember, managing proxies manually can be cumbersome. If you'd rather not manage proxy lists yourself, ProxyForge auto-tests and rotates proxies locally on your machine — one-off $29 unlock, no subscription:
https://proxyforge.dev/#download
With ProxyForge, you can focus on developing your scraping tasks without worrying about proxy management.
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 →