Scrapy with Residential Proxies: Middleware, Sessions and Errors
Route Scrapy through residential proxies: per-request meta proxy, a downloader middleware for country and sticky sessions, 402/407 handling, concurrency.
Exitway team··7 min read
Scrapy has proxy support built in. HttpProxyMiddleware reads request.meta["proxy"], and if the URL contains credentials it sends the Proxy-Authorization header for you. Routing one request through an Exitway residential IP takes one line. For a real project you want three more things: a small downloader middleware that builds the proxy username (country and session), a crawl that stops cleanly when the proxy says “no bandwidth” or “bad credentials”, and concurrency settings that suit residential exits.
Every snippet here was run against Scrapy 2.20. async def start() needs Scrapy 2.13 or later; on older versions, name it start_requests() and drop async.
One proxy per request with meta
Credentials come from environment variables (EXITWAY_USER, EXITWAY_PASS), and each request picks its own country:
import os
import scrapy
USER, PASS = os.environ["EXITWAY_USER"], os.environ["EXITWAY_PASS"]
def exitway(country=None, session=None, port=7777):
user = USER
if country:
user += f"-country-{country}"
if session:
user += f"-session-{session}"
return f"http://{user}:{PASS}@gw.exitway.net:{port}"
class CountrySpider(scrapy.Spider):
name = "countries"
async def start(self):
for country in ("us", "de", "jp"):
yield scrapy.Request(
"https://ipinfo.io/json",
meta={"proxy": exitway(country=country)},
cb_kwargs={"wanted": country},
dont_filter=True,
)
def parse(self, response, wanted):
yield {"wanted": wanted, "got": response.json()["country"].lower()}
Port 7777 is the residential product and 8888 is datacenter. Without a -session- parameter, every new connection gets a new IP.
This works, but watch what happens when the proxy refuses the tunnel. We ran it on an account with no residential bandwidth left:
ERROR: Gave up retrying <GET https://ipinfo.io/json> (failed 3 times): Could not open
CONNECT tunnel with proxy gw.exitway.net:7777 [{'status': 402, 'reason': b'Payment Required'}]
Scrapy’s RetryMiddleware treats TunnelError as transient and retries it. It retries a 402 (out of bandwidth) or a 407 (wrong credentials) the same way, and on a 100,000-URL crawl that means 300,000 pointless attempts. The middleware below fixes that.
A downloader middleware for Exitway
# exitway_proxy.py
import os
import uuid
from scrapy.core.downloader.handlers.http11 import TunnelError
from scrapy.exceptions import IgnoreRequest, NotConfigured
from scrapy.utils.defer import deferred_from_coro
GATEWAY = "gw.exitway.net"
FATAL = {402: "exitway_out_of_bandwidth", 407: "exitway_auth_failed", 400: "exitway_bad_parameters"}
class ExitwayProxyMiddleware:
def __init__(self, crawler):
s = crawler.settings
self.crawler = crawler
self.user = s.get("EXITWAY_USER") or os.environ.get("EXITWAY_USER")
self.password = s.get("EXITWAY_PASS") or os.environ.get("EXITWAY_PASS")
if not (self.user and self.password):
raise NotConfigured("set EXITWAY_USER and EXITWAY_PASS")
self.port = s.getint("EXITWAY_PORT", 7777) # 7777 residential, 8888 datacenter
self.country = s.get("EXITWAY_COUNTRY") # e.g. "us", None = any country
self.lifetime = s.getint("EXITWAY_LIFETIME", 30) # minutes, sticky only
self.sticky = s.getbool("EXITWAY_STICKY", False)
self.run_id = uuid.uuid4().hex[:10] # one sticky session per crawl
@classmethod
def from_crawler(cls, crawler):
return cls(crawler)
def _username(self, request):
user = self.user
country = request.meta.get("exitway_country", self.country)
if country:
user += f"-country-{country}"
session = request.meta.get("exitway_session") or (self.run_id if self.sticky else None)
if session:
user += f"-session-{session}-lifetime-{self.lifetime}"
return user
def process_request(self, request, spider=None):
if "proxy" not in request.meta: # an explicit meta["proxy"] wins
request.meta["proxy"] = f"http://{self._username(request)}:{self.password}@{GATEWAY}:{self.port}"
def process_response(self, request, response, spider=None):
# http:// targets: gateway errors arrive as responses carrying X-Exitway-Error
if response.headers.get("X-Exitway-Error") and response.status in FATAL:
self._abort(response.status)
return response
def process_exception(self, request, exception, spider=None):
# https:// targets: a refused CONNECT raises TunnelError; RetryMiddleware would retry it
if isinstance(exception, TunnelError):
for status in FATAL:
if f"'status': {status}" in str(exception):
self._abort(status)
def _abort(self, status):
reason = FATAL[status]
engine = self.crawler.engine
if hasattr(engine, "close_spider_async"): # recent Scrapy
deferred_from_coro(engine.close_spider_async(reason=reason))
else:
engine.close_spider(self.crawler.spider, reason)
raise IgnoreRequest(f"Exitway gateway returned {status} ({reason})")
Register it at priority 740:
process_requestruns in ascending order, so ours setsmeta["proxy"]just beforeHttpProxyMiddleware(750) turns it into a header.process_exceptionruns in descending order, so ours sees theTunnelErrorbeforeRetryMiddleware(550). RaisingIgnoreRequestthere ends the exception chain, which means no retry.
The gateway reports errors in two ways. For https:// targets, the refusal comes back on the CONNECT, which Scrapy surfaces as TunnelError. For http:// targets, it is a normal response with an X-Exitway-Error header. The middleware handles both. Retryable proxy errors (429, 502, 503, 504) still go to RetryMiddleware, and on a rotating username each retry opens a new connection from a new IP.
With an empty balance, the run now ends after the first wave of requests:
INFO: Closing spider (exitway_out_of_bandwidth)
The reason is also stored in the finish_reason stat, so a scheduler or alerting job can tell “top up” apart from “target broke”.
Rotating or sticky, per spider
Settings choose the default behavior. Spider custom_settings override it per spider:
import scrapy
class ExitIpSpider(scrapy.Spider):
name = "exit_ip"
custom_settings = {
"DOWNLOADER_MIDDLEWARES": {"exitway_proxy.ExitwayProxyMiddleware": 740},
"EXITWAY_COUNTRY": "us",
"EXITWAY_STICKY": False, # rotating: new IP per connection
}
async def start(self):
for _ in range(3):
yield scrapy.Request("https://ipinfo.io/json", dont_filter=True)
def parse(self, response):
data = response.json()
yield {"ip": data["ip"], "country": data["country"]}
Rotating is the right default for listing pages, search results and product catalogs: anything where requests don’t depend on each other. With EXITWAY_STICKY = True, the whole crawl shares one session and one IP for up to EXITWAY_LIFETIME minutes (1 to 1440). That is useful for a small site that ties pagination to a cookie, but drop CONCURRENT_REQUESTS_PER_DOMAIN to 1 or 2 so one IP isn’t hammering the site.
When different requests need different identities, for example QA flows on your own test accounts, set the session per request:
import scrapy
class AccountSpider(scrapy.Spider):
name = "accounts"
custom_settings = {
"DOWNLOADER_MIDDLEWARES": {"exitway_proxy.ExitwayProxyMiddleware": 740},
"EXITWAY_COUNTRY": "gb",
"EXITWAY_LIFETIME": 60,
}
async def start(self):
for n in range(3):
yield scrapy.Request(
"https://ipinfo.io/json",
meta={"exitway_session": f"acct{n}"}, # one IP per test account
dont_filter=True,
)
def parse(self, response):
session = response.meta["exitway_session"]
yield {"session": session, "ip": response.json()["ip"]}
# Follow-ups must carry the same id to stay on the same IP:
# yield response.follow("/account", meta={"exitway_session": session})
Session ids may contain letters and digits only, up to 32 characters. Anything else gets a 400, which the middleware reports as exitway_bad_parameters. Ids are private to your account, so another customer using acct1 never shares your IP. The rotating vs sticky sessions guide covers lifetimes and failover in detail.
Rotation is per connection, and Scrapy keeps connections open
Exitway assigns a new IP per TCP connection, and Scrapy reuses connections. Through a proxy, that means reusing the CONNECT tunnel. We counted tunnels for three sequential requests to one host: by default Scrapy opened one tunnel, so all three requests left from the same IP. With CONCURRENT_REQUESTS_PER_DOMAIN = 8 you are spread over up to 8 IPs at once, and each one changes whenever Scrapy opens a fresh connection. That is fine for most crawls, and cheaper, since you skip a TLS handshake per page.
If you need a new IP for every request, ask the target to close the connection after each response:
DEFAULT_REQUEST_HEADERS = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "en",
"Connection": "close", # new tunnel, so a new IP, for every request
}
The first two entries are Scrapy’s defaults. Setting this dict replaces them, so keep them. With this header, the same three requests opened three tunnels.
Concurrency settings that fit residential exits
DOWNLOADER_MIDDLEWARES = {"exitway_proxy.ExitwayProxyMiddleware": 740}
EXITWAY_PORT = 7777 # 7777 residential, 8888 datacenter
EXITWAY_COUNTRY = "us" # omit for any country
EXITWAY_STICKY = False # True = one IP for the whole crawl
EXITWAY_LIFETIME = 30 # minutes, only used when sticky
CONCURRENT_REQUESTS = 32
CONCURRENT_REQUESTS_PER_DOMAIN = 8
DOWNLOAD_DELAY = 0.25
AUTOTHROTTLE_ENABLED = True
AUTOTHROTTLE_TARGET_CONCURRENCY = 4.0
DOWNLOAD_TIMEOUT = 45
RETRY_TIMES = 3
RETRY_HTTP_CODES = [408, 429, 500, 502, 503, 504, 522, 524]
ROBOTSTXT_OBEY = True
| Setting | Why |
|---|---|
CONCURRENT_REQUESTS_PER_DOMAIN = 8 |
Rotation spreads requests across IPs, but the target still sees your total rate. |
AUTOTHROTTLE_ENABLED |
Residential latency varies by exit, and AutoThrottle adapts the delay to the latency it measures. |
DOWNLOAD_TIMEOUT = 45 |
The default is 180 s. A stalled exit should fail fast and be retried on a new IP. |
RETRY_TIMES = 3 |
With rotation, each retry is a fresh IP, so one more attempt is cheap. |
ROBOTSTXT_OBEY = True |
robots.txt is fetched through the same proxy, and Scrapy applies the site’s rules automatically. |
Concurrent connections are capped per account. If you raise CONCURRENT_REQUESTS past the cap, the gateway answers 429 too_many_connections with Retry-After: 5, and Scrapy retries it. Contact support if you need a higher cap rather than relying on that retry.
What the crawl costs
Exitway bills bytes in both directions, including TLS handshakes, at 1 GB = 1,000,000,000 bytes. A crawl of 200,000 HTML pages at 120 KB each is about 24 GB, or $16.80 at $0.70/GB on residential. Scrapy doesn’t execute JavaScript or fetch images, so it is one of the cheapest ways to use residential bandwidth. If your targets don’t block datacenter ranges, datacenter proxies at $0.30/GB are cheaper still: change EXITWAY_PORT to 8888.
Keep crawls to public data, respect robots.txt and rate limits, and stay within our Acceptable Use Policy.
Exitway residential proxies start at $0.70/GB, pay as you go, with bandwidth that never expires. See pricing, or create an account to get the credentials for EXITWAY_USER and EXITWAY_PASS.