requests is still the quickest way to fetch pages from Python, and it supports proxies out of the box. This guide covers the setup that works, the details that trip most people up (the https key, and environment variables that quietly win), proxy rotation, SOCKS5, and the patterns you'll want once you scale past a few requests.
The examples use the Residential Premium gateway prem.crawlproxies.com:3621 (HTTP only; the SOCKS5 section uses Residential Private). Grab your username and password from the generator and swap them in. Everything here was tested with requests 2.34.
Python requests proxy setup
Pass a proxies dict with both keys:
import requests
PROXY = "http://USERNAME:PASSWORD@prem.crawlproxies.com:3621"
proxies = {"http": PROXY, "https": PROXY}
r = requests.get("https://ipinfo.io/json", proxies=proxies, timeout=30)
print(r.status_code, r.json()["ip"], r.json()["country"])The #1 mistake: thehttpskey still uses anhttp://proxy URL. The key is the scheme of the website you're visiting; the value is how to reach the proxy. HTTPS sites are tunnelled through the proxy withCONNECT, so your traffic stays encrypted end to end.
Set both keys. With only "http" in the dict, every https:// URL skips the proxy and goes out from your own IP, with no error to warn you. Printing the IP from ipinfo.io, as above, is a quick way to check.
Always set a timeout. Without one, a single slow connection can hang your script forever.
How requests picks a proxy
The proxies dict maps a URL scheme to a proxy URL. A few more rules decide which proxy a request actually uses:
- Keys can name one site.
{"https://ipinfo.io": PROXY}sends only that host through the proxy; everything else goes direct. - Environment variables beat Session.proxies. If
HTTPS_PROXYis set in your shell, aSessionuses it instead of what you put ins.proxies. Aproxies=argument on the call itself still wins. Settrust_env = Falseto ignore the environment. - Special characters need encoding. A password with
@,:,/or#breaks the URL; an unencoded@showed up as a 407 in our test. Encode both parts withquote(..., safe="").
from urllib.parse import quote
import requests
user = "USERNAME-country-us"
password = "PASSWORD" # quote() makes p@ss:w/rd#1 safe too
PROXY = f"http://{quote(user, safe='')}:{quote(password, safe='')}@prem.crawlproxies.com:3621"
s = requests.Session()
s.trust_env = False # ignore HTTP_PROXY / HTTPS_PROXY from the environment
s.proxies = {"http": PROXY, "https": PROXY}
print(s.get("https://ipinfo.io/ip", timeout=30).text)Target a country or city
Targeting goes in the username, so it's just a string change:
def proxy_for(country=None, city=None):
user = "USERNAME"
if country:
user += f"-country-{country}"
if city:
user += f"-city-{city}"
url = f"http://{user}:PASSWORD@prem.crawlproxies.com:3621"
return {"http": url, "https": url}
r = requests.get("https://ipinfo.io/json", proxies=proxy_for("us", city="new_york"), timeout=30)
print(r.json()["city"]) # New YorkCountry codes are two letters (us, de, gb); cities are lowercase, with underscores for spaces (new_york, los_angeles). See the geo-targeting guide for the details.
Proxy rotation with requests
With no session in the username, each new connection gets a new IP. So rotation in requests comes down to when it opens a new connection:
- requests.get() opens a fresh connection on every call, so each call gets a new IP.
- A requests.Session keeps the connection open and reuses it. In our test, three calls through one session went through a single proxy tunnel, so they would all have left from the same IP.
To rotate inside a session, send Connection: close. The connection is dropped after each response, and the next request opens a new one:
s = requests.Session()
s.proxies = {"http": PROXY, "https": PROXY}
s.headers["Connection"] = "close" # new connection, so a new IP, on every request
for _ in range(3):
print(s.get("https://ipinfo.io/ip", timeout=30).text.strip()) # three different IPsRotate across a pool of sticky IPs
Sometimes you want a fixed number of IPs used in turn, for example one per account. Give each one its own session id and cycle through them:
import itertools
import uuid
def sticky(session_id, minutes=10):
url = f"http://USERNAME-country-us-ssid-{session_id}-sst-{minutes * 60}:PASSWORD@prem.crawlproxies.com:3621"
return {"http": url, "https": url}
pool = itertools.cycle([sticky(uuid.uuid4().hex[:8]) for _ in range(5)])
for url in ["https://example.com/a", "https://example.com/b", "https://example.com/c"]:
r = requests.get(url, proxies=next(pool), timeout=30)
print(r.status_code, url)Five IPs, each kept for 10 minutes, used in turn.
Rotate through a proxy list
Some plans give you a list of proxies instead of one gateway. Datacenter, for example, is a list of IPs, each used as IP:777 with your username and password. Download it from the generator in the http://user:pass@ip:port format and pick a line per request, moving on to another line when one fails:
import random
import requests
with open("proxies.txt", encoding="utf-8") as f: # one http://user:pass@ip:port per line
PROXIES = [line.strip() for line in f if line.strip()]
def get(url, tries=3):
for proxy in random.sample(PROXIES, k=min(tries, len(PROXIES))):
try:
return requests.get(url, proxies={"http": proxy, "https": proxy}, timeout=15)
except (requests.ConnectionError, requests.Timeout):
continue # try another line
raise RuntimeError(f"no working proxy for {url}")
print(get("https://ipinfo.io/ip").text)requests.ConnectionError covers proxy errors too (ProxyError is a subclass). The Datacenter list changes every few minutes, so download a fresh one for long jobs.
Sticky sessions
When you need the same IP across requests (a login, a cart, a multi-step form), add a session id and a duration in seconds:
import uuid
session_id = uuid.uuid4().hex[:8]
STICKY = f"http://USERNAME-country-us-ssid-{session_id}-sst-1800:PASSWORD@prem.crawlproxies.com:3621"
s = requests.Session()
s.proxies = {"http": STICKY, "https": STICKY}
print(s.get("https://ipinfo.io/ip", timeout=30).text)
print(s.get("https://ipinfo.io/ip", timeout=30).text) # same IP for up to 30 minutesThat's Residential Premium's form, up to 3600 seconds. Use a different session id per account or per worker. Sticky vs rotating sessions explains when to use which.
requests with a SOCKS5 proxy
requests needs an extra package for SOCKS. Install it once:
pip install "requests[socks]"Residential Premium is HTTP only, so SOCKS5 needs a plan that has it, such as Residential Private (priv.crawlproxies.com, SOCKS5 port 11000), with that plan's own username and password. Use the socks5h scheme:
import requests
SOCKS = "socks5h://USERNAME-country-us:PASSWORD@priv.crawlproxies.com:11000"
proxies = {"http": SOCKS, "https": SOCKS}
r = requests.get("https://ipinfo.io/json", proxies=proxies, timeout=30)
print(r.json()["ip"], r.json()["country"])socks5h, not socks5. With socks5h:// the proxy resolves the hostname, so DNS lookups don't come from your machine. With socks5:// your machine looks the name up first and only sends the proxy an IP address. We checked on a test SOCKS5 server: socks5h arrived as example.com, socks5 as a bare IP.
Residential Private writes targeting differently from Residential Premium. It takes a country and no city, and a sticky IP is -session-<id>-time-<seconds>, up to 2 hours:
SOCKS = "socks5h://USERNAME-country-us-session-cart42-time-1800:PASSWORD@priv.crawlproxies.com:11000"
s = requests.Session()
s.proxies = {"http": SOCKS, "https": SOCKS}
print(s.get("https://ipinfo.io/ip", timeout=30).text) # the same IP for 30 minutesRotation works as with HTTP: each new connection gets a new IP, and a Session reuses its connection.
Plans with a SOCKS5 port, and how each writes the username (your plan page shows the exact host and ports):
| Plan | SOCKS5 | Username example |
|---|---|---|
| Residential Premium | none (HTTP only, port 3621) | – |
| Residential Private | priv.crawlproxies.com:11000 | USERNAME-country-us-session-cart42-time-1800 |
| Residential | res.crawlproxies.com:9696 | USERNAME-session-cart42-time-600 (no location targeting) |
| Mobile (4G/5G) | geo.crawlproxies.com:1080 | USERNAME-country-us-session-cart42-time-1800 |
| Datacenter | each IP in your list, port 666 | USERNAME (no targeting) |
Retries with backoff
Residential IPs are real devices, so an occasional request will fail or a site will rate-limit you. Let urllib3 retry the transient cases with growing pauses:
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
retry = Retry(
total=4,
backoff_factor=1, # 1s, 2s, 4s, 8s between attempts
status_forcelist=[429, 500, 502, 503, 504],
allowed_methods=["GET", "HEAD"],
)
s = requests.Session()
s.mount("http://", HTTPAdapter(max_retries=retry))
s.mount("https://", HTTPAdapter(max_retries=retry))
s.proxies = proxies
r = s.get("https://example.com/", timeout=30)Only retry idempotent requests automatically. Retrying a POST that already went through can submit a form twice.
Many requests in parallel
requests is blocking, so use a thread pool to run requests side by side. Each requests.get call opens its own connection, and with a rotating username each connection has its own IP:
from concurrent.futures import ThreadPoolExecutor
urls = [f"https://example.com/page/{i}" for i in range(1, 51)]
def fetch(url):
try:
r = requests.get(url, proxies=proxies, timeout=30)
return url, r.status_code
except requests.RequestException as e:
return url, f"error: {e.__class__.__name__}"
with ThreadPoolExecutor(max_workers=10) as pool:
for url, status in pool.map(fetch, urls):
print(status, url)Start with 5 to 10 workers and raise it slowly while watching your error rate. Hammering one site from many IPs at once is still hammering it.
Environment variables
requests also honours the standard proxy variables, which is handy for tools you don't want to edit:
export HTTP_PROXY="http://USERNAME:PASSWORD@prem.crawlproxies.com:3621"
export HTTPS_PROXY="http://USERNAME:PASSWORD@prem.crawlproxies.com:3621"
python your_script.pyOn Windows PowerShell use $env:HTTPS_PROXY = "http://..." instead. Hosts listed in NO_PROXY skip the proxy. Remember that these variables override Session.proxies (see above).
Errors you might see
| Error | Usually means |
|---|---|
ProxyError ... Tunnel connection failed: 407 Proxy Authentication Required | Wrong username or password, a typo in the targeting part, or an unencoded @ or : in the password |
ProxyError ... Unable to connect to proxy with NewConnectionError | Wrong host or port, or a firewall blocking outbound connections |
SOCKS5 authentication failed | Wrong username or password on a SOCKS5 port, or targeting that plan doesn't accept |
ConnectTimeout from SOCKSHTTPSConnectionPool | A socks5h:// URL pointed at an HTTP port |
RemoteDisconnected('Remote end closed connection without response') | An http:// proxy URL pointed at a SOCKS5 port |
InvalidSchema: Missing dependencies for SOCKS support | Run pip install "requests[socks]" |
ConnectTimeout / ReadTimeout | A slow exit IP: retry it, and keep your timeouts sensible |
| The wrong IP in the response | Your own IP: no https key in proxies. Another proxy's IP: HTTPS_PROXY is overriding Session.proxies |
403 / 429 from the site | The site is blocking or rate-limiting: see our debugging checklist |
That's the whole toolkit. For browser automation in Python, Playwright takes the same credentials: see Playwright with authenticated proxies.



