Scrapy Proxy Guide: Rotation, Middleware and Sessions

Set a proxy on a Scrapy request in one line, then rotate it properly. Tested middleware for gateways and proxy lists, sticky sessions, SOCKS5 and errors.

To use a proxy in Scrapy, put its URL in request.meta["proxy"]. The built-in HttpProxyMiddleware is enabled by default and does the rest, for HTTP and HTTPS targets alike:

import scrapy


class IpSpider(scrapy.Spider):
    name = "ip"

    async def start(self):  # Scrapy 2.13+; use start_requests() on older versions
        yield scrapy.Request(
            "https://api.ipify.org?format=json",
            meta={"proxy": "http://USERNAME:PASSWORD@gw-rotating_datacenter.node4.io:8083"},
        )

    def parse(self, response):
        self.logger.info("exit IP: %s", response.json()["ip"])

Run it with scrapy runspider ip_spider.py. The log line shows the proxy's exit address instead of yours. That is the whole setup for one proxy. The rest of this guide covers what a real crawl needs next: authentication, rotation through a gateway or a list, sticky sessions, retries, concurrency, SOCKS5 and the errors you will meet.

Every sample here was run on Scrapy 2.20 against a local authenticating proxy, and the measurements quoted come from those runs.

Three ways to set a proxy in Scrapy

MethodScopeUse it when
meta={"proxy": url} on a requestOne requestA few requests need a proxy, or different requests need different ones
http_proxy and https_proxy environment variablesEvery request in the processA quick test with no code change
A downloader middleware that writes meta["proxy"]Every request, with logicRotation, sessions and retries: anything beyond one fixed proxy

Two rules decide which one wins. A proxy value in meta takes precedence over the environment variables, and it ignores no_proxy. Set both variables for a mixed crawl, because http_proxy covers only http:// targets and https_proxy only https:// ones:

export http_proxy="http://USERNAME:PASSWORD@gw-rotating_datacenter.node4.io:8083"
export https_proxy="$http_proxy"
scrapy crawl myspider

Proxy authentication: the URL or a Proxy-Authorization header

Put the username and password in the proxy URL. HttpProxyMiddleware takes them out, percent-decodes them, and sends them as a Proxy-Authorization: Basic header. It also rewrites meta["proxy"] without the credentials, so response.meta["proxy"] in your callback reads http://host:port and your logs do not leak the password.

Percent-encode a password that contains @, :, /, # or %:

from urllib.parse import quote

proxy = f"http://USERNAME:{quote('p@ss:w%rd', safe='')}@gw-rotating_datacenter.node4.io:8083"

Setting the header yourself also works, as long as the request has a proxy:

import base64

token = base64.b64encode(b"USERNAME:PASSWORD").decode()
yield scrapy.Request(
    url,
    meta={"proxy": "http://gw-rotating_datacenter.node4.io:8083"},
    headers={"Proxy-Authorization": f"Basic {token}"},
)

Prefer the URL form. Scrapy then manages the header for you, including removing it when a request changes proxy. Over HTTPS the header travels on the CONNECT request only, so the target site never sees it.

HTTP and HTTPS targets, and what "rotating" means over HTTPS

The scheme of the proxy URL describes how Scrapy talks to the proxy, not the site you scrape. Keep it http:// for both kinds of target. For an https:// page Scrapy sends the proxy a CONNECT request with your credentials, the proxy opens a tunnel, and TLS runs end to end inside it.

That tunnel is where most "my rotating proxy is not rotating" reports come from. A rotating gateway picks an exit per connection. On plain HTTP that is every request. On HTTPS it is every tunnel, and Scrapy keeps tunnels open and reuses them. Measured with 40 HTTPS requests to one site through one gateway URL, at default settings:

SetupTunnels openedExits you can see
Default (keep-alive)8At most 8, one per tunnel
Connection: close on each request40A new pick per request
One session id11, on purpose

Eight is CONCURRENT_REQUESTS_PER_DOMAIN. Scrapy opens up to that many tunnels to a site and sends every later request down one of them. For many crawls that is fine: the load is spread over several exits and you skip a TLS handshake per request. When each request must get its own pick, send Connection: close, which the middleware below does with one setting.

A Scrapy proxy middleware for a rotating gateway

A gateway is one hostname with a pool behind it, so there is no proxy list to manage in Python. The middleware has three jobs: write the proxy on every pass, keep one exit for requests that share a session, and make a blocked or failed request retry on a different exit.

# settings.py
DOWNLOADER_MIDDLEWARES = {
    "myproject.middlewares.GatewayProxyMiddleware": 570,
}

PROXY_USER = "USERNAME"
PROXY_PASS = "PASSWORD"
PROXY_ENDPOINT = "gw-rotating_datacenter.node4.io:8083"

PROXY_BAN_CODES = [403, 429]           # statuses that mean "this exit is blocked"
PROXY_BAN_MARKERS = []                 # e.g. ["captcha-delivery.com"] for block pages served as 200
PROXY_NEW_TUNNEL_PER_REQUEST = False   # True: a new exit pick for every HTTPS request

RETRY_TIMES = 4
# myproject/middlewares.py
import logging
import uuid
from urllib.parse import quote

from scrapy.downloadermiddlewares.retry import get_retry_request
from scrapy.exceptions import IgnoreRequest, NotConfigured

logger = logging.getLogger(__name__)


class GatewayProxyMiddleware:
    """Send every request through one rotating gateway endpoint.

    Rotation is the default. A request with meta["proxy_session"] keeps one
    exit. A blocked or failed request is retried on a newly picked exit.
    """

    def __init__(self, crawler):
        s = crawler.settings
        self.crawler = crawler
        self.user = s.get("PROXY_USER")
        self.endpoint = s.get("PROXY_ENDPOINT")
        if not (self.user and s.get("PROXY_PASS") and self.endpoint):
            raise NotConfigured("set PROXY_USER, PROXY_PASS and PROXY_ENDPOINT")
        self.password = quote(s.get("PROXY_PASS"), safe="")
        self.ban_codes = {int(c) for c in s.getlist("PROXY_BAN_CODES", [403, 429])}
        self.ban_markers = [m.encode() for m in s.getlist("PROXY_BAN_MARKERS")]
        self.new_tunnel_per_request = s.getbool("PROXY_NEW_TUNNEL_PER_REQUEST")

    @classmethod
    def from_crawler(cls, crawler):
        return cls(crawler)

    def process_request(self, request, spider=None):
        if request.meta.get("proxy_off"):
            return None
        session = request.meta.get("proxy_session")
        user = f"{self.user}-session-{session}" if session else self.user
        # Written on every pass, so a retry never inherits a stale choice.
        request.meta["proxy"] = f"http://{user}:{self.password}@{self.endpoint}"
        if self.new_tunnel_per_request and not session:
            # Close the tunnel after this response: the next request opens a
            # new one and the gateway picks a new exit for it.
            request.headers["Connection"] = "close"
        return None

    def process_response(self, request, response, spider=None):
        if request.meta.get("proxy_off"):
            return response
        blocked = response.status in self.ban_codes or any(
            marker in response.body for marker in self.ban_markers
        )
        if not blocked:
            return response
        self._new_exit(request)
        retry = get_retry_request(
            request, spider=self.crawler.spider, reason=f"blocked ({response.status})"
        )
        return retry or response  # out of retries: let the spider see it

    def process_exception(self, request, exception, spider=None):
        if request.meta.get("proxy_off") or isinstance(exception, IgnoreRequest):
            return None
        if "407" in str(exception):
            logger.error("The proxy rejected the credentials (407). Fix PROXY_USER / PROXY_PASS.")
            return None
        self._new_exit(request)
        return None  # RetryMiddleware (550) reschedules the request

    def _new_exit(self, request):
        # Different credentials force a new tunnel, and a new session id makes
        # the gateway pick a new exit. The retry copies this meta.
        request.meta["proxy_session"] = uuid.uuid4().hex[:12]

Three details in it are easy to get wrong.

The priority is 570, not the 350 or 610 most tutorials use. Request hooks run in ascending order and response and exception hooks in descending order. The slot between RetryMiddleware (550) and HttpCompressionMiddleware (590) gives you all three things at once: your process_request runs before HttpProxyMiddleware (750) turns the credentials into a header, your process_exception runs before RetryMiddleware copies the failed request, and your process_response sees the body after it has been decompressed. At 610 the same marker check ran against gzip bytes in testing and missed a block page. At 760 requests reached the proxy without credentials.

The proxy is written on every pass. A retry is a copy of the failed request, meta included. A middleware that skips requests which already have a proxy sends every retry back to the choice that just failed.

A retry needs a new tunnel, not just a new attempt. Scrapy retries a 503 or 429 down the same pooled tunnel, so it leaves from the same exit. The tested fix is the last method: Scrapy pools tunnels per proxy credential, so a fresh session id in the username forces a new tunnel, and the gateway picks a new exit for a session id it has not seen.

Point PROXY_ENDPOINT at the product you hold. The middleware is the same for all three:

Node4 productPROXY_ENDPOINTBilled byEntry plan
Rotating Datacentergw-rotating_datacenter.node4.io:8083Gigabyte$5.90/month for 10 GB ($0.59/GB)
Rotating Unmeteredgw-rotating_unmetered.node4.io:8084Concurrent connections$29.00/month for 250 connections ($0.116 per connection)
Residentialgw-residential.node4.io:8082Gigabyte$4.99/month for 3 GB ($1.66/GB)

The two rotating products draw the same datacenter exits in the United States, Italy and Spain; only the meter differs. Which one fits a given crawl is covered on proxies for Scrapy, with the full ladders on the rotating pricing page.

Rotate a proxy list or pool with your own middleware

If you hold a list of static addresses instead of a gateway, the middleware picks one per request and stops choosing an address that fails:

# settings.py
DOWNLOADER_MIDDLEWARES = {"myproject.middlewares.ProxyListMiddleware": 570}
PROXY_LIST = [
    "http://USERNAME:PASSWORD@HOST1:PORT",
    "http://USERNAME:PASSWORD@HOST2:PORT",
]
PROXY_COOLDOWN = 300  # seconds an address rests after a connection failure
# myproject/middlewares.py
import logging
import random
import time

from scrapy.exceptions import IgnoreRequest, NotConfigured

logger = logging.getLogger(__name__)


class ProxyListMiddleware:
    """Rotate a static list. Bench an address that fails, retry it later."""

    def __init__(self, proxies, cooldown):
        if not proxies:
            raise NotConfigured("PROXY_LIST is empty")
        self.proxies = proxies
        self.cooldown = cooldown
        self.benched_until = {}

    @classmethod
    def from_crawler(cls, crawler):
        s = crawler.settings
        return cls(s.getlist("PROXY_LIST"), s.getfloat("PROXY_COOLDOWN", 300))

    def process_request(self, request, spider=None):
        now = time.monotonic()
        live = [p for p in self.proxies if self.benched_until.get(p, 0) <= now]
        # If everything is benched, use the full list instead of stalling.
        choice = random.choice(live or self.proxies)
        request.meta["proxy"] = choice
        # HttpProxyMiddleware strips the credentials out of meta["proxy"],
        # so keep our own copy to know which entry carried this request.
        request.meta["proxy_choice"] = choice
        return None

    def process_exception(self, request, exception, spider=None):
        choice = request.meta.get("proxy_choice")
        if choice is None or isinstance(exception, IgnoreRequest):
            return None
        self.benched_until[choice] = time.monotonic() + self.cooldown
        logger.warning(
            "benched %s for %ss after %s",
            choice.rsplit("@", 1)[-1],
            self.cooldown,
            type(exception).__name__,
        )
        return None  # RetryMiddleware reschedules; the next pass picks again

In the test run, a four-entry list with one address that dropped connections and one that refused them finished all 12 requests on the two healthy entries after 7 retries.

Bench on connection errors only. A 403 says the target dislikes the request, not that the address is down, and benching on it empties the list against any site that blocks at all. On a static list a 403 usually means the whole range is classified, which is the case for a rotating gateway or residential exits rather than more cycling.

scrapy-rotating-proxies and similar packages

PackageLatest release on PyPIWhat it does
scrapy-rotating-proxies0.6.2, May 2019Rotates a list, detects bans, rechecks dead proxies with backoff
scrapy-proxy-pool0.1.9, March 2020Rotates free public proxies it fetches itself
scrapy-proxies0.4, October 2017Picks a random proxy from a file per request

scrapy-rotating-proxies still runs on Scrapy 2.20 and rotated the test list correctly. It also logs deprecation warnings that its hooks "will not be passed" a spider argument "in future Scrapy versions", so pin your Scrapy version if you depend on it.

Use it when you have a large list of static proxies and want ban tracking without writing it. Skip it in three cases:

  • You use a gateway. The package treats the one endpoint as one proxy. Its default policy counts every status other than 200, 301 and 302 as a ban, and an empty 200 too, so a single 404 marks your only "proxy" dead.
  • You tuned concurrency per site. With the package enabled, CONCURRENT_REQUESTS_PER_DOMAIN, DOWNLOAD_DELAY and AutoThrottle apply per proxy instead of per site.
  • You need sessions. It has no notion of keeping one address for a sequence of requests.

Sticky sessions: one exit per cookiejar

A login, a cart or a paginated listing needs every request in the sequence to leave from one address. On Node4 gateways you ask for that in the proxy username: USERNAME-session-a1b2c3. Requests carrying the same id leave from the same exit, and the middleware above builds that username whenever a request has proxy_session in its meta.

Pair each session with its own Scrapy cookiejar, so one address always presents one set of cookies:

import uuid

import scrapy


class ListingsSpider(scrapy.Spider):
    name = "listings"

    async def start(self):
        for category in ("lamps", "rugs", "chairs"):
            session = uuid.uuid4().hex[:12]
            yield scrapy.Request(
                f"https://example.com/c/{category}",
                meta={"proxy_session": session, "cookiejar": session},
            )

    def parse(self, response):
        for title in response.css("h2.product::text").getall():
            yield {"title": title}

        next_url = response.css("a.next::attr(href)").get()
        if next_url:
            # meta is not inherited by follow-up requests: pass both keys on.
            keep = {k: response.meta[k] for k in ("proxy_session", "cookiejar")}
            yield response.follow(next_url, meta=keep)

In the test run each category kept one tunnel and its own cookies across three pages. Leave out the meta on response.follow and page two quietly returns to rotation.

The limits to design around:

  • On Rotating Datacenter and Rotating Unmetered a session id holds its exit for up to 30 minutes from first use. Activity does not extend the window, and after it the same id resolves to a new exit with no error. Give each task its own id and keep tasks shorter than the window.
  • On residential a session is best effort with a 30-minute ceiling, because the exit is a consumer device that can go offline. Use letters and digits only, up to 32 characters. The same username takes country and city segments, described in residential country and city targeting.
  • If the middleware replaces a session after a block, the retry continues on a new address. For a target that binds a cursor to the address, restart that chain from page one in an errback instead.

If you set DOWNLOAD_DELAY, give each session its own download slot. All requests to one site share one slot by default, so three sessions queue behind each other. Adding request.meta["download_slot"] = f"session-{session}" in process_request cut a nine-request, three-session test with a one-second delay from 8.2 seconds to 2.1. When to pin and when to rotate is covered in sticky versus rotating sessions.

Retries and ban detection

Scrapy's defaults, and what they mean behind a proxy:

SettingDefaultBehind a proxy
RETRY_TIMES2Raise to 4 or 5: each retry on a new exit is a nearly independent attempt
RETRY_HTTP_CODES408, 429, 500, 502, 503, 504, 522, 524403 is not in it. Let the middleware decide, through PROXY_BAN_CODES
DOWNLOAD_TIMEOUT180 secondsLower to 30. A dead route should fail fast and retry elsewhere

A block arrives in three shapes. A status code such as 403 or 429 is the easy one. A connection error or timeout is retried by Scrapy on its own. The third is a 200 whose body is a challenge page, which no status check catches. Find a string that appears only on the block page and add it to PROXY_BAN_MARKERS. The middleware then retries that response on a new exit, up to RETRY_TIMES.

Changing the address fixes blocks that are counted per address. It does not fix a request that looks automated: default headers, no cookies, machine timing. If a new exit is blocked within a few pages, work through why your IP is getting blocked before spending more retries.

Concurrency: CONCURRENT_REQUESTS, AutoThrottle and plan limits

SettingDefaultWhat it controls
CONCURRENT_REQUESTS16Requests in flight across the whole crawl
CONCURRENT_REQUESTS_PER_DOMAIN8Requests in flight per site, and so the tunnels Scrapy keeps open to it
DOWNLOAD_DELAY0Pause between requests to one site
AUTOTHROTTLE_ENABLEDFalseAdjusts the delay from the latency it measures

How these meet your plan depends on its meter:

  • Per-gigabyte plans (Rotating Datacenter, residential). Concurrency sets how fast you spend the allowance. Run a bounded slice of the crawl, read the bytes it moved on the dashboard, and size the plan from that.
  • Rotating Unmetered. The plan is a number of concurrent connections, and an open tunnel holds one even while idle. Scrapy keeps idle tunnels for 240 seconds by default. Keep CONCURRENT_REQUESTS under the plan's number, and remember that every session id holds its own tunnel until it idles out. A connection over the limit is refused with a 429, which Scrapy reports as a TunnelError. The connection limits guide shows how to read the live count.

Through a rotating pool, latency mostly reflects which exit a tunnel drew, not how loaded the target is. AutoThrottle reads a slow exit as a struggling server and backs off. Leave it on as a conservative default for a site you do not know, or switch it off and set a DOWNLOAD_DELAY you chose.

Rotation spreads requests across addresses, so each address stays under a per-address rate limit. It does not make the site's total load smaller. Raise per-site concurrency in steps and watch the share of blocked responses as you go.

SOCKS5 proxies in Scrapy

Scrapy's default download handler does not speak SOCKS. Given socks5://USERNAME:PASSWORD@host:port, it sent an HTTP CONNECT to the SOCKS port in testing and failed with ConnectionDone: Connection was closed cleanly. What works:

  1. Use the proxy's HTTP port. This is the right answer for almost every Scrapy crawl. Node4 serves HTTP and SOCKS5 on every paid plan with the same credentials, and an HTTPS page through an HTTP proxy is still encrypted end to end inside the tunnel.
  2. Switch to the HTTPX download handler (Scrapy 2.15 and later). It supports SOCKS5, and Scrapy's documentation labels it experimental:
# pip install "scrapy[httpx]"
DOWNLOAD_HANDLERS = {
    "http": "scrapy.core.downloader.handlers._httpx.HttpxDownloadHandler",
    "https": "scrapy.core.downloader.handlers._httpx.HttpxDownloadHandler",
}
# then, per request:
# meta={"proxy": "socks5://USERNAME:PASSWORD@gw-rotating_datacenter.node4.io:1083"}

In the test run this handler authenticated to a SOCKS5 proxy and passed the target hostname to it with both socks5:// and socks5h://, so DNS was resolved at the proxy and not on the local machine. It keeps a separate connection pool per proxy URL, which adds up when you use many session ids. Protocol trade-offs are in SOCKS5 proxy setup.

Scrapy proxy errors and their fixes

What you seeCauseFix
TunnelError: Could not open CONNECT tunnel ... 'status': 407Wrong credentials on an HTTPS target. Scrapy retries it RETRY_TIMES times before giving upCheck username, password and encoding. See fixing 407 errors
HttpError: Ignoring non-200 response with status 407The same, on a plain-HTTP target. Not retriedAs above
TunnelError ... 'status': 429 on Rotating UnmeteredEvery connection on the plan is in useLower CONCURRENT_REQUESTS, or move to a larger plan
TunnelError ... 'status': 502The gateway has no exit for the requested country, or could not reach the targetCheck the country code, then retry
ConnectionDone: Connection was closed cleanlyA socks5:// URL on the default handlerUse the HTTP port or the HTTPX handler
DownloadConnectionRefusedErrorWrong proxy host or portCopy the endpoint from the dashboard's Proxies page
DownloadTimeoutError after three minutesA dead route with the default timeoutSet DOWNLOAD_TIMEOUT = 30
ValueError: invalid hostname or unauthenticated requestsYour middleware runs after HttpProxyMiddlewareUse a priority below 750
The same IP on every HTTPS requestTunnel reuse, or a session id on every requestPROXY_NEW_TUNNEL_PER_REQUEST = True, or drop the session
The IP changes in the middle of a paginationmeta was not passed to the next requestPass proxy_session in response.follow
The proxy is ignoredHTTPPROXY_ENABLED = False, or meta["proxy"] is NoneRe-enable it, and set the key on every request

On older Scrapy versions the timeout and refusal surface as Twisted's TimeoutError and ConnectionRefusedError. The causes and fixes are the same.

Which Node4 plan to point your spider at

Start with Rotating Datacenter when the target accepts datacenter addresses: $5.90/month for 10 GB ($0.59/GB). Move to Rotating Unmetered when bytes, not connections, would decide the bill; it starts at $29.00/month for 250 connections ($0.116 per connection). Use residential proxies when the target refuses datacenter ranges: $4.99/month for 3 GB ($1.66/GB). These are Node4's standard monthly prices.

You can prove the list middleware before paying. The free tier provisions 3 free shared proxies with 1 GB/month bandwidth and 10 concurrent threads, static and HTTP only, so point PROXY_LIST at them. The gateways need a paid plan.

Proxies for Scrapy compares the products for a crawl, and a runnable project built the same way is in the Scrapy folder of the Node4 examples repository. If your client is requests or httpx instead, use the Python proxy integration guide.