How to Rotate Proxies in Python
By the Proxy11 team. Updated .
The Python SDK gives you a requests session that picks a proxy for each request. This is the whole setup, followed by the parts that usually catch people out.
pip install proxy11 requests
import os
import requests
from proxy11 import ProxyClient
client = ProxyClient(os.environ["PROXY11_API_KEY"])
session = client.session(country="us", proxy_type="anonymous")
try:
response = session.get("https://httpbin.org/ip", timeout=(5, 15))
except requests.exceptions.ProxyError:
# The failed proxy is removed from the pool; retry once with the next one.
response = session.get("https://httpbin.org/ip", timeout=(5, 15))
response.raise_for_status()
print(response.json())
What the session rotates
Before each request the SDK takes an ip:port from a list it fetched earlier. When that list runs out, client.session() fetches another batch. A request that has already started stays on its proxy.
A dead proxy raises an error
After a ProxyError the session drops that proxy and raises the error to you. It does not retry by itself, so if your job should carry on, catch the error and send the request again, as the example does.
A 403 or 429 is different. That is the target site answering, so the proxy itself is alive. Handle those as a block from the site, not as a dead proxy.
Keep the key out of your code
Read it from PROXY11_API_KEY as shown, and keep it out of Git and shared logs. Also keep passwords and payment details off public proxies, because whoever runs the proxy can see any traffic that isn't encrypted.