Scrapy Proxy Middleware: Auth, Rotation and Throttling

Learn how to use a scrapy proxy with built-in middleware, credentials, rotating dongles, AutoThrottle, retries, and safe debugging steps now.
A 4G USB dongle connects through a small computer and cloud router to a globe.

A scrapy proxy lets your spider send requests through an HTTP or SOCKS5 endpoint, while Scrapy handles the request and response flow. This guide shows how to configure one proxy, add credentials safely, spread requests across several 4G dongles, and keep the crawl polite with AutoThrottle.

What you need before adding a proxy

Have these pieces ready before changing your spider:

  1. A Scrapy project that already works without a proxy. Prove the selectors and pagination first so you can isolate proxy problems later.
  2. An HTTP proxy endpoint in host:port form, plus credentials if your endpoint uses authentication. ProxyKite’s proxy format guide shows the supported formats.
  3. Permission to crawl the target and a clear request rate. A proxy changes the network path; it does not remove the target site’s terms, robots rules, or rate limits.
  4. Environment variables for secrets. Do not commit a username, password, or rotation URL to settings.py or a public repository.

If you are building the endpoints yourself, a Huawei E3372 HiLink dongle on a Raspberry Pi is the reference setup for ProxyKite. The licence is software and cloud routing; you provide the dongles, SIMs, and mobile data plans.

How Scrapy picks a proxy

Scrapy’s built-in HttpProxyMiddleware looks for a proxy in two places: the lowercase http_proxy and https_proxy environment variables, or the request’s meta["proxy"] value. The per-request value takes precedence and can look like http://host:port or http://user:pass@host:port.

The normal proxy URL uses the http:// scheme even when the destination is an HTTPS website. The proxy creates the tunnel; the destination’s TLS connection still protects the HTTPS request. SOCKS URLs need a compatible download handler, so start with an HTTP endpoint when using Scrapy’s standard handler. See the official HttpProxyMiddleware documentation for the current handler details.

Step 1: Test one proxy on one request

Why: a single request proves the endpoint, port, and network path before you add authentication or rotation.

Add the proxy to a request in your spider:

import scrapy


PROXY = "http://proxy.example:8080"


class QuotesSpider(scrapy.Spider):
    name = "quotes"
    allowed_domains = ["quotes.toscrape.com"]
    start_urls = ["https://quotes.toscrape.com/"]

    def start_requests(self):
        for url in self.start_urls:
            yield scrapy.Request(url, meta={"proxy": PROXY})

    def parse(self, response):
        for quote in response.css("div.quote"):
            yield {
                "text": quote.css("span.text::text").get(),
                "author": quote.css("small.author::text").get(),
            }

Run the spider as usual:

scrapy crawl quotes -O quotes.json

Success looks like normal 200 responses and a populated output file. If the first request fails, test the endpoint outside Scrapy before changing spider code:

curl -x "http://proxy.example:8080" https://httpbin.org/ip

The response should show the proxy’s public address, not the address of the machine running Scrapy. Treat a public IP check as a diagnostic only; it does not prove that the target site accepts the crawl.

Step 2: Add proxy authentication without leaking secrets

Why: credentials in a proxy URL are understood by HttpProxyMiddleware, but special characters must be URL-encoded and secrets should come from the process environment.

Set the values in your shell or secret manager:

export PROXY_USER="crawler-user"
export PROXY_PASS="use-a-secret-store"

Build the URL once when the spider starts:

import os
from urllib.parse import quote


proxy_user = quote(os.environ["PROXY_USER"], safe="")
proxy_pass = quote(os.environ["PROXY_PASS"], safe="")
PROXY = f"http://{proxy_user}:{proxy_pass}@proxy.example:8080"

Use that PROXY value in every request. quote(..., safe="") matters when a password contains characters such as @, :, #, or /; otherwise the URL parser can mistake part of the password for the host or port. A 407 Proxy Authentication Required response usually means the credentials are wrong, the endpoint expects a different authentication mode, or the URL was not encoded.

Success looks like the request passing the proxy without a 407, while the password remains absent from source control and normal application logs.

Step 3: Keep the proxy on follow-up requests

Why: assigning meta["proxy"] to the first request does not make it a project-wide policy. Follow-up requests need the setting too, or a middleware must add it for you.

For a small spider, pass the same metadata when following a link:

def parse(self, response):
    for quote in response.css("div.quote"):
        yield {
            "text": quote.css("span.text::text").get(),
            "author": quote.css("small.author::text").get(),
        }

    next_page = response.css("li.next a::attr(href)").get()
    if next_page:
        yield response.follow(
            next_page,
            callback=self.parse,
            meta={"proxy": PROXY},
        )

For a crawl with many callbacks, this repetition is easy to miss. That is the point at which a downloader middleware is safer: the spider produces ordinary requests, and one central component applies the proxy policy.

Success looks like pagination and callback requests continue through the intended endpoint instead of silently falling back to a direct connection.

Step 4: Set AutoThrottle and concurrency

Why: rotating IPs does not make a high request rate polite. The destination still receives your total traffic, and bursts can trigger 429 responses even when every request uses a different address.

Start with a conservative project configuration:

The relevant lines in settings.py are:

ROBOTSTXT_OBEY = True

CONCURRENT_REQUESTS = 16
CONCURRENT_REQUESTS_PER_DOMAIN = 2
DOWNLOAD_DELAY = 1
DOWNLOAD_TIMEOUT = 30

AUTOTHROTTLE_ENABLED = True
AUTOTHROTTLE_START_DELAY = 5
AUTOTHROTTLE_MAX_DELAY = 60
AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
AUTOTHROTTLE_DEBUG = True

These are starting values, not a promise that every site should receive two parallel requests. Reduce concurrency for a sensitive target. Increase it only after you have checked the site’s rules, response quality, and server load.

AutoThrottle uses response latency to adjust each download slot. It cannot make a slow target faster, and it does not replace a hard concurrency limit. Its target is an average, not a guaranteed request count. The official AutoThrottle documentation explains how delays are calculated and why error responses do not reduce the delay.

Success looks like the Scrapy log showing changing slot delays while the crawl remains within your chosen concurrency ceiling. Turn AUTOTHROTTLE_DEBUG off after tuning so routine logs stay readable.

Step 5: Spread requests over several dongles

Why: a small downloader middleware keeps proxy selection out of every spider callback and gives each request a consistent selection rule.

Create yourproject/middlewares.py:

class ProxyPoolMiddleware:
    def __init__(self, proxies):
        self.proxies = proxies
        self.position = 0

    @classmethod
    def from_crawler(cls, crawler):
        return cls(crawler.settings.getlist("PROXY_POOL"))

    def process_request(self, request, spider):
        # Keep a manually selected proxy for a login or multi-step session.
        if request.meta.get("proxy_locked") or not self.proxies:
            return None

        request.meta["proxy"] = self.proxies[self.position % len(self.proxies)]
        self.position += 1
        return None

Load the endpoint URLs from the environment in settings.py:

import os


PROXY_POOL = [
    os.environ["PROXY_ONE"],
    os.environ["PROXY_TWO"],
    os.environ["PROXY_THREE"],
]

DOWNLOADER_MIDDLEWARES = {
    "yourproject.middlewares.ProxyPoolMiddleware": 740,
}

In the current Scrapy settings, the built-in HttpProxyMiddleware is at order 750. Placing this selector at 740 lets it set request.meta["proxy"] immediately before the built-in middleware consumes that value. Scrapy runs process_request() in increasing order, so check the current downloader middleware order after a major upgrade.

This example uses round-robin selection. It is easier to reason about than random choice and gives each configured endpoint a turn. It does not promise that a target will see a new address for every request: a 4G network can keep an address for a while, and a service may reuse a shared endpoint. For sessions that need continuity, assign one proxy yourself and mark the request:

yield scrapy.Request(
    account_url,
    callback=self.parse_account,
    meta={
        "proxy": os.environ["PROXY_ONE"],
        "proxy_locked": True,
    },
)

Success looks like your Scrapy startup log listing yourproject.middlewares.ProxyPoolMiddleware and requests continuing when one endpoint is not selected. Log a safe proxy identifier or index while debugging, never the complete URL with credentials.

Step 6: Rotate between crawl batches when sessions matter

Why: per-request rotation is useful for independent pages, but it can break a workflow where several requests belong to one session. Batch rotation gives you a clear boundary: finish one group, rotate, then start the next group.

Use one gateway endpoint in Scrapy and trigger its rotation control between batches. The proxy URL stays the same in request.meta; the routing service changes the mobile path behind it. For ProxyKite, use the rotation control documented in the rotation API guide, and review the practical proxy rotation link walkthrough before wiring it into a job queue.

A safe batch workflow is:

  1. Select a bounded group of URLs for one session or job.
  2. Crawl that group through the current proxy endpoint.
  3. Record the response status, retry count, and the public IP if your diagnostic endpoint permits it.
  4. Call the rotation control according to the API guide.
  5. Start the next group only after the rotation request succeeds.

Do not rotate just because a page returned a normal application-level 404. Rotate only at a workflow boundary or when your retry policy identifies a temporary network or rate-limit condition. If you need one address to remain stable for several days, the sticky versus rotating proxy guide explains the session trade-off.

Success looks like one batch completes, the rotation control returns success, and the next batch starts only after the new route is ready.

Verify the complete setup

Run these checks in order:

  1. One endpoint: curl -x succeeds with the same host, port, and credentials that Scrapy uses.
  2. One spider request: the first response is received through meta["proxy"].
  3. Follow-up requests: pagination and callbacks still carry the proxy, or the central middleware assigns one.
  4. Pool selection: a short test logs proxy indexes such as 0, 1, 2, 0, without logging secrets.
  5. Target behavior: the target’s status codes, Retry-After headers, and crawl rules are being respected.
  6. Rotation boundary: a batch rotation returns success before the next batch begins.

If you are using your own 4G farm, ProxyKite turns each active dongle into an HTTP and SOCKS5 endpoint and can route it without a static IP or inbound port forwarding. The ProxyKite homepage has the product overview; you still supply the hardware, SIMs, and data plans.

Troubleshooting Scrapy proxy errors

SymptomLikely causeWhat to check
407 Proxy Authentication RequiredWrong credentials or malformed URLURL-encode both username and password; confirm the endpoint’s auth mode.
Connection refused or timeoutHost, port, route, or dongle path is unavailableRun the same endpoint with curl -x, then check the dongle and powered hub.
The target still sees the direct addressMiddleware is not enabled or the proxy is only on the first requestCheck the startup middleware list and every follow-up request.
All requests use one endpointThe pool setting has one value, or the request is marked proxy_lockedPrint the safe index selected by the middleware.
Many 429 responsesThe total request rate is too highLower concurrency, keep AutoThrottle enabled, and respect Retry-After.
Repeated 403 responsesThe target rejected the request for a policy, content, header, or access reasonStop and inspect the response and crawl permission; do not blindly add retries to evade an access control.
SOCKS5 is unsupportedThe default download handler does not handle that schemeUse an HTTP endpoint or configure a compatible handler documented by Scrapy.

Scrapy retries connection failures and several temporary HTTP statuses by default. If your legitimate crawl needs to retry a 403 that clearly represents a temporary rate-limit policy, add it deliberately and keep the count low:

RETRY_TIMES = 2
RETRY_HTTP_CODES = [403, 408, 429, 500, 502, 503, 504, 522, 524]

Do not treat retries as a way around a site’s access controls. A new proxy does not make an unauthorized crawl acceptable, and repeated retries can increase the load you are trying to reduce.

FAQ

How do I set a proxy in Scrapy?

Set meta={"proxy": "http://host:port"} on the request, or set the lowercase http_proxy and https_proxy environment variables. The built-in HttpProxyMiddleware applies the value for the standard HTTP download handler.

How do I add username and password to a Scrapy proxy?

Put the URL-encoded username and password before the host, such as http://user:pass@host:port. Read both from environment variables and use urllib.parse.quote(..., safe="") so special characters cannot corrupt the proxy URL.

Does Scrapy rotate proxies automatically?

No. Scrapy applies the proxy you provide; it does not choose a new endpoint by itself. Use a downloader middleware for a pool of dongle endpoints, or use a service rotation control between batches while keeping the gateway URL stable.

Should I use one proxy for every Scrapy request?

Use one proxy when the workflow needs a stable session or when you are testing the spider. For independent pages, a small pool can distribute traffic, but keep concurrency and AutoThrottle limits based on the target site rather than the number of IPs.

Can I use a SOCKS5 proxy with Scrapy?

Only with a download handler that supports SOCKS. Scrapy’s current documentation identifies HttpxDownloadHandler as the built-in option for SOCKS, while the standard handler is the simpler choice for an HTTP proxy endpoint.

Previous Article

4G Data Throttling: How to Test a Proxy Dongle

Next Article

UPS for a Proxy Farm: Size Backup Power and Recover Cleanly