Python requests Proxy Rotation: A Complete Tutorial
Introduction
When working with web scraping or automation tasks that involve making HTTP requests to external websites, you may encounter situations where your IP address is blocked due to too many requests being sent from the same source. To circumvent this issue, proxy rotation is a common technique used by developers. This guide will walk you through how to implement proxy rotation in Python using the requests library, complete with error handling to ensure robustness.
Setting Up Your Environment
Before we dive into the code, make sure you have Python installed on your machine. You can download it from the official website if you haven't already. Additionally, install the requests library if you haven't done so:
pip install requests
Proxy Rotation Basics
Proxy rotation involves sending HTTP requests through a list of proxies rather than using a single IP address. This can help avoid being blocked by websites that monitor and block traffic from specific IPs.
Here's a basic example of how to set up proxy rotation using the requests library:
import requests
# List of proxies
proxies = [
'http://proxy1.example.com:8080',
'http://proxy2.example.com:8080',
'http://proxy3.example.com:8080'
]
def get_response(url, proxy):
try:
response = requests.get(url, proxies={'http': proxy, 'https': proxy})
return response
except requests.exceptions.RequestException as e:
print(f"Error with proxy {proxy}: {e}")
return None
# Example usage
url = 'https://example.com'
for proxy in proxies:
response = get_response(url, proxy)
if response and response.status_code == 200:
print("Success:", response.text[:100]) # Print first 100 characters of the response
break
else:
print("All proxies failed")
Implementing Error Handling
In a production environment, it's crucial to handle errors gracefully. This includes handling network issues, invalid proxy responses, and any other exceptions that might occur.
Here’s an enhanced version of the previous code with more detailed error handling:
import requests
from time import sleep
proxies = [
'http://proxy1.example.com:8080',
'http://proxy2.example.com:8080',
'http://proxy3.example.com:8080'
]
def get_response(url, proxy):
try:
response = requests.get(url, proxies={'http': proxy, 'https': proxy}, timeout=5)
response.raise_for_status() # Raises an HTTPError for bad responses
return response
except requests.exceptions.HTTPError as http_err:
print(f"HTTP error occurred: {http_err}")
except requests.exceptions.ConnectionError as conn_err:
print(f"Connection error occurred: {conn_err}")
except requests.exceptions.Timeout as timeout_err:
print(f"Timeout error occurred: {timeout_err}")
except requests.exceptions.RequestException as req_err:
print(f"An error occurred: {req_err}")
return None
# Example usage
url = 'https://example.com'
for proxy in proxies:
response = get_response(url, proxy)
if response and response.status_code == 200:
print("Success:", response.text[:100]) # Print first 100 characters of the response
break
else:
print("All proxies failed")
# Optional: Add a delay between requests to avoid overwhelming the server
sleep(1)
Advanced Proxy Rotation Strategies
For more advanced scenarios, you might want to implement strategies such as retrying with different proxies after failures, or cycling through proxies in a round-robin fashion.
Here's an example of how you could implement a simple round-robin proxy rotation:
import requests
from itertools import cycle
proxies = [
'http://proxy1.example.com:8080',
'http://proxy2.example.com:8080',
'http://proxy3.example.com:8080'
]
def get_response(url, proxy):
try:
response = requests.get(url, proxies={'http': proxy, 'https': proxy}, timeout=5)
response.raise_for_status()
return response
except requests.exceptions.RequestException as e:
print(f"Error with proxy {proxy}: {e}")
return None
# Example usage
url = 'https://example.com'
for proxy in cycle(proxies): # Cycle through proxies indefinitely
response = get_response(url, proxy)
if response and response.status_code == 200:
print("Success:", response.text[:100])
break
Conclusion
Proxy rotation is a powerful technique for maintaining anonymity and avoiding IP bans while scraping websites or automating tasks. By using the requests library in Python, you can easily implement proxy rotation with error handling to ensure your application remains robust.
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 →