![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](/images/blog/scrapy-proxy-setup.cleaned.webp)
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.
# 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:
| Scrapy crawl workload | Recommended IPMusk product | Key routing behavior |
|---|---|---|
| Public product catalogs, docs mirrors, and wide web discovery | Rotating 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 cookies | Static 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 ASNs | Datacenter (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.
RETRY_ENABLED = True
RETRY_TIMES = 2
RETRY_HTTP_CODES = [408, 429, 500, 502, 503, 504, 522, 524]
HTTPPROXY_AUTH_ENCODING = "utf-8"Sources checked
- Scrapy HttpProxyMiddleware source (process_request, _get_proxy, _set_proxy_and_creds): github.com/scrapy/scrapy/blob/master/scrapy/downloadermiddlewares/httpproxy.py
- Scrapy RetryMiddleware source (RETRY_HTTP_CODES, RETRY_TIMES): github.com/scrapy/scrapy/blob/master/scrapy/downloadermiddlewares/retry.py
- Scrapy Downloader Middleware and Settings docs: docs.scrapy.org/en/latest/topics/downloader-middleware.html and docs.scrapy.org/en/latest/topics/settings.html
- IPMusk product pages and diagnostics: ipmusk.com/pricing/residential, ipmusk.com/pricing/isp, ipmusk.com/pricing/datacenter, and ipmusk.com/tools/proxy-checker
All Scrapy source files, documentation pages, and IPMusk pricing/tool URLs verified HTTP 200 on December 4, 2026.
