Tutorials

How to Use a Proxy with Scrapy

By IPMusk TeamUpdated 3 min read

Attach a custom downloader middleware at a lower order number than Scrapy's built-in HttpProxyMiddleware (default 750) and assign request.meta['proxy'] from environment variables. Scrapy automatically extracts username and password into a Basic Proxy-Authorization header, strips credentials from request.meta['proxy'], and cleans stale auth state when routes change. Keep HTTP proxy endpoints for HttpProxyMiddleware, route high-volume crawls via Rotating Residential and stateful targets via Static ISP, and stop immediately on 407 auth errors.

IPMusk Scrapy proxy guide diagram showing custom Downloader Middleware setting request.meta['proxy'] before HttpProxyMiddleware, Rotating Residential vs. Static ISP routing, and bounded retry handling
Scrapy proxy routing architecture: inject request.meta['proxy'] ahead of HttpProxyMiddleware (750), split Rotating Residential vs. Static ISP lines, and isolate 407 auth failures from bounded retries.

Set request.meta['proxy'] before HttpProxyMiddleware (order 750)

Scrapy enables HttpProxyMiddleware by default at priority 750 whenever HTTPPROXY_ENABLED is true (the built-in setting). Inside process_request(), HttpProxyMiddleware reads either request.meta['proxy'] or OS http_proxy / https_proxy variables, parses embedded credentials into a Basic Proxy-Authorization header, and resets request.meta['proxy'] to scheme://host:port without credentials.

If you want clean per-request routing across crawls or spiders without leaking credentials into logs or stale headers into fallback requests, place a small custom middleware right before 750 (for example, at priority 740) and let HttpProxyMiddleware handle credential encoding and header cleanup:

  • Keep IPMUSK_PROXY_URL in deployment secrets or server environment variables instead of committing credentials into settings.py.
  • Use HTTP proxy URLs (http://gate.ipmusk.com:31212 for Rotating Residential, or your assigned Static ISP host and port) because Scrapy's built-in HttpProxyMiddleware uses Twisted's HTTP proxy handler rather than SOCKS5.
  • HttpProxyMiddleware defaults HTTPPROXY_AUTH_ENCODING to 'latin-1'; set HTTPPROXY_AUTH_ENCODING = 'utf-8' if credentials ever include UTF-8 characters.
Python: custom Scrapy Downloader Middleware and settings (syntax checked)
# middlewares.py
class ProxyRoutingMiddleware:
    """Assign an HTTP proxy URL per request before HttpProxyMiddleware (750)."""

    def __init__(self, proxy_url: str | None) -> None:
        self.proxy_url = proxy_url

    @classmethod
    def from_crawler(cls, crawler):
        return cls(proxy_url=crawler.settings.get("IPMUSK_PROXY_URL"))

    def process_request(self, request, spider):
        if self.proxy_url and "proxy" not in request.meta:
            request.meta["proxy"] = self.proxy_url

# settings.py
import os

BOT_NAME = "docs_crawler"
CONCURRENT_REQUESTS = 8
DOWNLOAD_TIMEOUT = 25

IPMUSK_PROXY_URL = os.environ.get(
    "IPMUSK_PROXY_URL",
    "http://USERNAME:PASSWORD@gate.ipmusk.com:31212",
)

DOWNLOADER_MIDDLEWARES = {
    "myproject.middlewares.ProxyRoutingMiddleware": 740,
    "scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware": 750,
}

Match Rotating Residential and Static ISP to crawl behavior

High-concurrency crawls against public catalogs behave differently from regional portal checks or authenticated sessions that rely on cookie persistence. Routing both workloads through one proxy tier either exhausts metered residential traffic unnecessarily or breaks long-lived sessions when IPs rotate mid-crawl.

Select your IPMusk product line per spider or per request metadata override:

Proxy line selection for Scrapy spiders and middlewares
Scrapy crawl workloadRecommended IPMusk productKey routing behavior
Public product catalogs, docs mirrors, and wide web discoveryRotating Residential (from $2.99 for 1 GB Trial; down to $0.80/GB at 1,000 GB)Connects via gate.ipmusk.com:31212 with per-request rotation or 1/3/10/30-min sticky exits; country and available state selection
Regional dashboards, login flows, or long session cookiesStatic ISP (Native ISP or ISP from $3.99/IP per 30 days)Dedicated assigned IP with fixed host and port, unmetered traffic, and 30 or 90 day renewal
Permissive feeds accepting hosting ASNsDatacenter (from $2.99/IP per 30 days)Lowest-cost unmetered assigned IP when targets accept datacenter ranges

IPMusk proxy connections authenticate via username and password only; IP allowlisting is not supported. Build country or available state credential strings on your workspace Connect screen or via build_proxy_url in MCP.

Bound RetryMiddleware and catch 407 before writing items

Scrapy's built-in RetryMiddleware (priority 550) retries codes listed in RETRY_HTTP_CODES (defaults to [408, 429, 500, 502, 503, 504, 522, 524]) up to RETRY_TIMES (default 2 retries after the initial request). Notice that HTTP 407 (Proxy Authentication Required) is outside default retry codes, which is good: retrying bad credentials wastes proxy attempts and can fail spiders noisily.

Configure retry limits explicitly and test credentials separately before scaling spider concurrency:

  • HTTP 407 Proxy Authentication Required: stop the spider immediately and check host, port, and credentials with IPMusk's Proxy Checker (/tools/proxy-checker) or review /blog/proxy-error-407.
  • HTTP 403 Forbidden: Scrapy does not retry 403 by default; check whether your spider omits browser headers or hits a datacenter ASN block (/blog/proxy-403-forbidden) before adding proxy overrides.
  • HTTP 429 Too Many Requests: pair AutoThrottle or per-domain DOWNLOAD_DELAY with bounded retries (/blog/proxy-429-too-many-requests) instead of raising RETRY_TIMES blindly.
  • Pipeline hygiene: inspect response.status in spiders (when handle_httpstatus_list is enabled) so block interstitials never enter JSONL, Parquet, or RAG Item Pipelines.
Python: explicit Scrapy retry and encoding bounds in settings.py (syntax checked)
RETRY_ENABLED = True
RETRY_TIMES = 2
RETRY_HTTP_CODES = [408, 429, 500, 502, 503, 504, 522, 524]
HTTPPROXY_AUTH_ENCODING = "utf-8"

Sources checked

All Scrapy source files, documentation pages, and IPMusk pricing/tool URLs verified HTTP 200 on December 4, 2026.