Tutorials10 min readOct 11, 2026

Scrapy rotating proxies: proxy middleware and IP rotation

Rotating proxies in Scrapy: set a proxy per request, write a proxy middleware, rotate the IP per request or from a list, and keep sticky sessions.

By crawlproxies
Scrapy rotating proxies: proxy middleware and IP rotation

Scrapy already knows how to use proxies: put a proxy URL in a request's meta and its built-in HttpProxyMiddleware does the rest, including the username and password. This guide starts there, wraps it in a small proxy middleware so every request gets a proxy, then covers proxy rotation (and why Scrapy can quietly send a whole crawl from one IP), rotating through a proxy list, sticky sessions, geo-targeting and crawl settings.

You'll need your crawlproxies username and password from the generator. The examples use the Residential Premium gateway prem.crawlproxies.com:3621 (HTTP). They were tested with Scrapy 2.19.

Set a proxy on a Scrapy Request

For a quick test, set the proxy on one request:

python
import scrapy

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

    async def start(self):
        yield scrapy.Request(
            "https://ipinfo.io/json",
            meta={"proxy": "http://USERNAME:PASSWORD@prem.crawlproxies.com:3621"},
        )

    def parse(self, response):
        yield response.json()

Scrapy reads the credentials from the URL and sends them as Proxy-Authorization for you. HTTPS sites are tunnelled through the proxy with CONNECT, so the page itself stays encrypted.

Older tutorials use start_requests(). Scrapy 2.13 replaced it with async def start(), and since 2.16 start_requests() isn't called at all: a spider that only defines it finishes with 0 pages and no error. On Scrapy older than 2.13, write def start_requests(self): instead.

Three things to know about the proxy key:

  • The proxy URL starts with http://, even for HTTPS sites. It says how to reach the proxy, not the site. An https:// proxy URL fails with NotImplementedError: HTTPS proxies for HTTPS destinations are not supported.
  • Scrapy's default downloader has no SOCKS5 support. A socks5:// URL isn't rejected: each request hangs until DOWNLOAD_TIMEOUT, because Scrapy talks HTTP to the SOCKS port. Use your plan's HTTP port. Every crawlproxies plan with a SOCKS5 port has one too, with the same login. (Scrapy 2.19 also ships an experimental httpx-based downloader that can use SOCKS, but it's marked as not ready for production.)
  • Encode special characters. A password with @, :, / or # breaks the URL. Encode it with urllib.parse.quote(password, safe=""); Scrapy decodes it before building the header.

Scrapy proxy middleware

Rather than touching every request, add a downloader middleware that sets the proxy for you. It builds the username from optional meta keys, so targeting and sessions stay one key away. In middlewares.py:

python
from urllib.parse import quote


class CrawlproxiesMiddleware:
    """Send every request through the crawlproxies gateway.

    Optional request.meta keys:
      proxy_country = "us"        exit country (two-letter code)
      proxy_city = "new_york"     exit city, together with a country
      proxy_session = "cart42"    keep the same IP for this session id
      proxy_session_ttl = 1800    how long to keep it, in seconds (up to 3600)
    """

    def __init__(self, user, password, host, country=None):
        self.user, self.password, self.host, self.country = user, password, host, country

    @classmethod
    def from_crawler(cls, crawler):
        s = crawler.settings
        return cls(s.get("PROXY_USER"), s.get("PROXY_PASSWORD"),
                   s.get("PROXY_HOST", "prem.crawlproxies.com:3621"), s.get("PROXY_COUNTRY"))

    def process_request(self, request, spider=None):
        if "proxy" in request.meta:           # a proxy set on the request wins
            return None
        user = self.user
        country = request.meta.get("proxy_country", self.country)
        if country:
            user += f"-country-{country}"
            if request.meta.get("proxy_city"):
                user += f"-city-{request.meta['proxy_city']}"
        if request.meta.get("proxy_session"):
            ttl = request.meta.get("proxy_session_ttl", 1800)
            user += f"-ssid-{request.meta['proxy_session']}-sst-{ttl}"
        request.meta["proxy"] = f"http://{quote(user, safe='')}:{quote(self.password, safe='')}@{self.host}"
        return None

Enable it in settings.py. Its number must be below 750, so it runs before Scrapy's own HttpProxyMiddleware, which turns the URL into the Proxy-Authorization header:

python
DOWNLOADER_MIDDLEWARES = {
    "myproject.middlewares.CrawlproxiesMiddleware": 350,
}

PROXY_USER = "USERNAME"
PROXY_PASSWORD = "PASSWORD"
PROXY_COUNTRY = "us"          # or None for worldwide

Keep real credentials out of version control. Read them from the environment in settings.py with os.environ["PROXY_PASSWORD"].

Two details in the code:

  • spider=None. Since Scrapy 2.14, a middleware whose process_request() requires the spider argument gets a ScrapyDeprecationWarning. The default value silences it and still works on older versions.
  • A proxy already in meta wins. That lets one request use another plan. It's also why you shouldn't build follow-up requests with meta=response.meta. That copies the old proxy URL plus Scrapy's internal _auth_proxy key, and in our test the follow-up request went out without credentials and failed with a 407. Pass on only the keys you need, such as meta={"proxy_session": "acct7"}.

Target a country or city per request

The middleware reads the location from meta, so one spider can crawl several countries:

python
yield scrapy.Request("https://example.com/de/", meta={"proxy_country": "de"})
yield scrapy.Request("https://example.com/us/", meta={"proxy_country": "us", "proxy_city": "new_york"})
yield scrapy.Request("https://example.com/", meta={"proxy_country": None})   # worldwide

Country codes are two letters; cities are lowercase, with underscores for spaces (new_york, los_angeles). The geo-targeting guide lists the options.

Rotating proxies in Scrapy

A rotating gateway does the rotation for you. Without a session in the username, every new connection gets a new exit IP, so you don't need a list of proxies or a rotation package: one endpoint is enough.

The catch is that Scrapy keeps connections open and reuses them. Requests with the same proxy username go through the same tunnel whenever one is free, and a tunnel keeps its IP. In our test with DOWNLOAD_DELAY = 0.5 and one request at a time, eight requests to one site all went through a single tunnel, so they would all have left from the same IP.

Rotate the IP on every request

To give every request its own IP, stop Scrapy from reusing the tunnel. The simplest way is a Connection: close header, which makes Scrapy drop the connection after the response:

python
yield scrapy.Request(url, headers={"Connection": "close"})

For a whole spider, add it to the default headers in custom_settings, keeping the two that Scrapy sends by default:

python
class PricesSpider(scrapy.Spider):
    name = "prices"
    custom_settings = {
        "DEFAULT_REQUEST_HEADERS": {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "Accept-Language": "en",
            "Connection": "close",
        },
    }

A unique short session per request does the same job. Each session id makes a different username, and Scrapy never shares a tunnel between different proxy credentials:

python
import uuid

def fresh_ip(url, **kwargs):
    """A request with its own short sticky session, so it gets its own exit IP."""
    meta = {"proxy_session": uuid.uuid4().hex[:10], "proxy_session_ttl": 60}
    return scrapy.Request(url, meta=meta, **kwargs)

Both cost a new connection (and TLS handshake) per request, so only use them when every request really needs a fresh IP. For most crawls, rotating per connection is plenty.

Rotate proxies from an IP 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. Rotation then means picking another line. Download the list from the generator in the http://user:pass@ip:port format, save it as proxies.txt, and add this middleware:

python
import random


class ProxyListMiddleware:
    """A random proxy from a list for every request, and a new one on every retry."""

    def __init__(self, proxies):
        self.proxies = proxies

    @classmethod
    def from_crawler(cls, crawler):
        path = crawler.settings.get("PROXY_LIST_FILE", "proxies.txt")
        with open(path, encoding="utf-8") as f:
            return cls([line.strip() for line in f if line.strip()])

    def process_request(self, request, spider=None):
        if "proxy" in request.meta and not request.meta.get("from_proxy_list"):
            return None                        # a proxy set on the request wins
        request.meta["proxy"] = random.choice(self.proxies)
        request.meta["from_proxy_list"] = True
        return None

    def process_exception(self, request, exception, spider=None):
        bad = request.meta.get("proxy")
        if request.meta.get("from_proxy_list") and bad in self.proxies and len(self.proxies) > 1:
            self.proxies.remove(bad)           # stop using a line that failed
        return None                            # RetryMiddleware retries with another line
python
DOWNLOADER_MIDDLEWARES = {
    "myproject.middlewares.ProxyListMiddleware": 610,
}
PROXY_LIST_FILE = "proxies.txt"

The number matters here. At 610, process_request still runs before HttpProxyMiddleware (750), and process_exception runs before RetryMiddleware (550) retries the request. So a line that refuses connections is dropped, and the retry picks another one.

The Datacenter list changes every few minutes, so download a fresh one before each run.

What about the scrapy-rotating-proxies package?

scrapy-rotating-proxies rotates a list too, with ban detection and back-off for dead proxies. Its last release is from 2019. Version 0.6.2 still worked with Scrapy 2.19 in our test, but it logs deprecation warnings. It reads the same file:

python
DOWNLOADER_MIDDLEWARES = {
    "rotating_proxies.middlewares.RotatingProxyMiddleware": 610,
    "rotating_proxies.middlewares.BanDetectionMiddleware": 620,
}
ROTATING_PROXY_LIST_PATH = "proxies.txt"

With a rotating gateway you don't need it.

Sticky sessions for stateful crawls

Most crawls are happy with rotating IPs. When a spider has to log in or walk through a multi-step flow, pin those requests to one IP with a session id, and keep using the same id for the follow-up requests:

python
async def start(self):
    yield scrapy.Request("https://example.com/login", callback=self.login,
                         meta={"proxy_session": "acct7"})

def login(self, response):
    yield scrapy.FormRequest.from_response(
        response, formdata={"username": "me", "password": "secret"},
        callback=self.after_login, meta={"proxy_session": "acct7"},
    )

Use a different session id per account. The IP stays for proxy_session_ttl seconds (30 minutes by default in the middleware, up to 3600 on Residential Premium). See sticky vs rotating sessions for patterns.

The middleware writes Residential Premium's tokens. On Residential Private (priv.crawlproxies.com, HTTP port 10000) a session is -session-<id>-time-<seconds> instead, up to 7200, and there is no city. Change those two lines if that's your plan.

Settings that keep you unblocked

A proxy hides where you are, not how fast you go. These settings matter as much as the IPs:

python
CONCURRENT_REQUESTS = 32
CONCURRENT_REQUESTS_PER_DOMAIN = 8
DOWNLOAD_DELAY = 0.5              # seconds between requests to the same site

AUTOTHROTTLE_ENABLED = True       # adapts the delay to how the site responds
AUTOTHROTTLE_START_DELAY = 1
AUTOTHROTTLE_TARGET_CONCURRENCY = 4

RETRY_ENABLED = True
RETRY_TIMES = 3
RETRY_HTTP_CODES = [429, 500, 502, 503, 504, 522, 524, 408]
DOWNLOAD_TIMEOUT = 30

ROBOTSTXT_OBEY = True
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/154.0.0.0 Safari/537.36"

Scrapy already varies the delay at random (between 0.5 and 1.5 times DOWNLOAD_DELAY). Don't add RANDOMIZE_DOWNLOAD_DELAY: Scrapy 2.19 deprecates it. Copy the USER_AGENT from a current browser; an outdated one stands out.

AutoThrottle slows down when the site slows down, which is exactly what a polite crawler should do.

Troubleshooting

SymptomFix
TunnelError: Could not open CONNECT tunnel with 'status': 407Wrong username or password, a token the gateway doesn't accept (Residential Premium sessions are -ssid-/-sst-, not -session-/-time-), or a request built with meta=response.meta
TunnelError with another statusThe proxy refused the tunnel: check that the plan is active and has bandwidth left
DownloadTimeoutError on every requestOften a socks5:// URL or a SOCKS5 port: Scrapy's default downloader only speaks HTTP proxies
NotImplementedError: HTTPS proxies for HTTPS destinations are not supportedWrite the proxy URL with http://
ConnectionRefusedErrorWrong host or port
Every response from the same IPScrapy is reusing the tunnel: see "Rotate the IP on every request" above
ScrapyDeprecationWarning: ... requires a spider argumentGive process_request a default: spider=None
The spider finishes with 0 pages and no errorScrapy 2.16+ no longer calls start_requests(): rename it to async def start(self)
Lots of 403 / 429Lower concurrency and add delay; see the debugging checklist
Middleware has no effectIts number must be below 750, the module path must match your project, and the request mustn't already carry a proxy

Need a headless browser inside Scrapy for JavaScript-heavy pages? The same username format works in Playwright.

Written by
crawlproxies
Create account