Scrapy sends every request through HttpProxyMiddleware, which reads the proxy from the request's meta. Per-request assignment looks like this:
yield scrapy.Request(
url,
meta={"proxy": "http://USER:PASS@GATEWAY:PORT"},
)
With a rotating gateway that is all you need — the provider swaps exit IPs server-side. The rest of this guide is about doing rotation yourself when you have several gateways, and surviving bans.
A minimal rotating middleware
Add this middleware and it assigns a gateway to every request that has none:
# middlewares.py
import random
GATEWAYS = [
"http://USER:PASS@GW1:PORT",
"http://USER:PASS@GW2:PORT",
]
class RandomProxyMiddleware:
def process_request(self, request, spider):
if "proxy" not in request.meta:
request.meta["proxy"] = random.choice(GATEWAYS)
# settings.py
DOWNLOADER_MIDDLEWARES = {
"myproject.middlewares.RandomProxyMiddleware": 760, # HttpProxyMiddleware is 750 — stay after it
}
HttpProxyMiddleware is at 750. Register yours at 750+1 or higher so your meta["proxy"] assignment is what the built-in middleware reads. If you set a lower number, you will fight it.Retry with a different IP on ban
Scrapy's RetryMiddleware retries the same request — same proxy, same fate. Extend it to drop the proxy on ban-flavoured failures:
from scrapy.downloadermiddlewares.retry import RetryMiddleware
class BanAwareRetryMiddleware(RetryMiddleware):
def process_response(self, request, response, spider):
if response.status in (403, 429) and request.meta.get("proxy"):
request.meta["proxy"] = random.choice(GATEWAYS) # force a new gate/IP
return super().process_response(request, response, spider)
def process_exception(self, request, exception, spider):
if isinstance(exception, (TimeoutError, ConnectionError)) and request.meta.get("proxy"):
request.meta["proxy"] = random.choice(GATEWAYS)
return super().process_exception(request, exception, spider)
Also raise the retry budget for hostile targets:
RETRY_ENABLED = True
RETRY_TIMES = 4
RETRY_HTTP_CODES = [500, 502, 503, 504, 403, 429, 408]
Sticky sessions per spider or per user
When a site ties content to session cookies, the same exit IP must serve the whole flow. Most residential gateways accept a session token in the username:
def sticky_proxy(sid: str) -> str:
return "http://USER-session-%s:PASS@GATEWAY:PORT" % sid
request.meta["proxy"] = sticky_proxy(spider.name + "-%d" % (hash(request.url) % 1000))
SOCKS5 in Scrapy
Install the extra and use socks5h:// so DNS resolves on the proxy side:
pip install scrapy[socks]
request.meta["proxy"] = "socks5h://USER:PASS@GATEWAY:PORT"
Throttle for residential pools
Residential exits drop and renumber constantly. AutoThrottle plus generous timeouts keeps the crawl alive:
AUTOTHROTTLE_ENABLED = True
AUTOTHROTTLE_START_DELAY = 1.0
AUTOTHROTTLE_MAX_DELAY = 15
DOWNLOAD_TIMEOUT = 30
CONCURRENT_REQUESTS = 16
CONCURRENT_REQUESTS_PER_DOMAIN = 4
Debugging checklist
- All requests share one exit IP — your middleware order is wrong (see the note above) or
meta["proxy"]was overwritten TimeoutErrorstorms — connect timeout too low for distant exits; raiseDOWNLOAD_TIMEOUT- Bans return 200 with a challenge page — Scrapy sees success; add content verification in
process_response(anchor text check) before retrying Proxy 407— credentials in the gateway URL; URL-encode special characters
FAQ
Does Scrapy rotate proxies automatically?
No. Scrapy reads the proxy from request.meta via HttpProxyMiddleware but never changes it. Rotation is either done by a rotating gateway server-side or by your own middleware assigning different gateways per request.
What order should my proxy middleware use?
Register your middleware at 751 or higher. HttpProxyMiddleware sits at 750, and a later process_request can set or overwrite request.meta['proxy'] before the built-in middleware consumes it.
How do I avoid reusing a banned IP?
Extend RetryMiddleware: on 403/429 responses or connection exceptions, replace request.meta['proxy'] before the retry fires, and add a session token so the gateway allocates a fresh exit IP.
Can Scrapy use SOCKS5 proxies?
Yes, after pip install scrapy[socks]. Use socks5h:// so DNS resolves on the proxy side and you avoid DNS leaks.
Need a pool to rotate against? IPLight's rotating residential gateway gives you 170+ countries from $1.20/GB — see pricing, or check the live pool report first.