IP Rotation in Python with requests: A Production-Ready Implementation
IP Rotation in Python with requests: A Production-Ready Implementation
Introduction
Running web scraping and automation tasks at scale often requires rotating IP addresses to avoid getting blocked by target websites. This guide will walk you through implementing a production-grade proxy rotation system using Python, specifically focusing on the requests library and extending it with httpx for session management.
We'll build a ProxyRotator class that handles thread-safe cycling of proxies, tracks failures, automatically excludes problematic proxies, and manages sessions efficiently. This setup will help you maintain reliable connectivity even as your proxy list grows or degrades over time.
Setting Up Your Environment
Before diving into the code, ensure you have the necessary Python libraries installed:
pip install requests httpx
For this guide, we'll use requests for basic HTTP operations and httpx for more advanced session management and asynchronous capabilities. However, keep in mind that httpx is not strictly required; it's an optional enhancement.
Implementing the ProxyRotator Class
The ProxyRotator class will manage a pool of proxies, cycling through them as requests are made. It will also track failures and exclude proxies that fail too many times consecutively.
Basic Structure
Here's the basic structure of our ProxyRotator class:
import random
from threading import Lock
class ProxyRotator:
def __init__(self, proxy_list, max_failures=3):
self.proxy_list = proxy_list
self.max_failures = max_failures
self.failures = {}
self.lock = Lock()
def get_proxy(self):
with self.lock:
# Filter out proxies that have failed too many times
active_proxies = [proxy for proxy in self.proxy_list if self.failures.get(proxy, 0) < self.max_failures]
if not active_proxies:
raise ValueError("All proxies are currently blacklisted due to repeated failures.")
# Return a random proxy from the active list
return random.choice(active_proxies)
def report_failure(self, proxy):
with self.lock:
# Increment failure count for this proxy
self.failures[proxy] = self.failures.get(proxy, 0) + 1
def reset_proxy(self, proxy):
with self.lock:
# Reset the failure count for a given proxy
if proxy in self.failures:
del self.failures[proxy]
Usage Example
Here's how you can use the ProxyRotator class to make requests:
import requests
def fetch_data(url, proxy_rotator):
proxy = proxy_rotator.get_proxy()
try:
response = requests.get(url, proxies={"http": proxy, "https": proxy})
response.raise_for_status()
return response.text
except requests.RequestException as e:
print(f"Request failed with {proxy}: {e}")
proxy_rotator.report_failure(proxy)
# Optionally retry with a new proxy or handle the error as needed
# Example usage
if __name__ == "__main__":
proxies = [
"http://proxy1.example.com:8080",
"http://proxy2.example.com:8080",
"http://proxy3.example.com:8080"
]
rotator = ProxyRotator(proxies)
for _ in range(10):
data = fetch_data("https://example.com", rotator)
if data:
print(data)
Extending with `httpx` for Session Management
While requests is powerful, httpx offers more advanced features such as asynchronous requests and better performance under load. Here's how you can integrate it into your proxy rotation system:
import httpx
class ProxyRotatorHttpx:
def __init__(self, proxy_list, max_failures=3):
self.proxy_list = proxy_list
self.max_failures = max_failures
self.failures = {}
self.lock = Lock()
def get_proxy(self):
with self.lock:
active_proxies = [proxy for proxy in self.proxy_list if self.failures.get(proxy, 0) < self.max_failures]
if not active_proxies:
raise ValueError("All proxies are currently blacklisted due to repeated failures.")
return random.choice(active_proxies)
def report_failure(self, proxy):
with self.lock:
self.failures[proxy] = self.failures.get(proxy, 0) + 1
def reset_proxy(self, proxy):
with self.lock:
if proxy in self.failures:
del self.failures[proxy]
def fetch_data_httpx(url, proxy_rotator):
proxy = proxy_rotator.get_proxy()
try:
with httpx.Client(proxies={"http://": proxy, "https://": proxy}) as client:
response = client.get(url)
response.raise_for_status()
return response.text
except (httpx.RequestError, httpx.HTTPStatusError) as e:
print(f"Request failed with {proxy}: {e}")
proxy_rotator.report_failure(proxy)
# Example usage with httpx
if __name__ == "__main__":
proxies = [
"http://proxy1.example.com:8080",
"http://proxy2.example.com:8080",
"http://proxy3.example.com:8080"
]
rotator_httpx = ProxyRotatorHttpx(proxies)
for _ in range(10):
data = fetch_data_httpx("https://example.com", rotator_httpx)
if data:
print(data)
Upgrading to Paid Rotating Residential Proxies
As your free proxy list fails under scale or becomes insufficient, consider upgrading to a paid rotating residential proxy service. Two options are:
- Bright Data Zone Endpoint: Offers high anonymity and can be used with HTTP headers for session management.
- SmartProxy Rotating Endpoint: Provides robust failover and automatic IP rotation.
To use these services, you'll need their API credentials. Here's a basic example using httpx to connect to Bright Data:
def fetch_data_with_bright_data(url, api_key):
proxy_url = f"http://{api_key}@zproxy.luminati.io:80"
try:
with httpx.Client(proxies={"http://": proxy_url, "https://": proxy_url}) as client:
response = client.get(url)
response.raise_for_status()
return response.text
except (httpx.RequestError, httpx.HTTPStatusError) as e:
print(f"Request failed: {e}")
# Example usage with Bright Data
if __name__ == "__main__":
api_key = "YOUR_BRIGHT_DATA_API_KEY"
data = fetch_data_with_bright_data("https://example.com", api_key)
if data:
print(data)
Replace "YOUR_BRIGHT_DATA_API_KEY" with your actual API key from Bright Data.
Conclusion
Building a robust proxy rotation system in Python is essential for maintaining reliable web scraping and automation tasks. The ProxyRotator class provides a solid foundation, managing proxies efficiently with thread-safe operations, failure tracking, and automatic exclusion of failing proxies.
As you scale up, consider upgrading to paid residential proxy services like Bright Data or SmartProxy for enhanced reliability and anonymity. These services offer comprehensive solutions that can handle large-scale tasks more effectively than free proxies.
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 →