How to use a proxy with Scrapy
Scrapy routes a request through a proxy when request.meta["proxy"] is set; the built-in HttpProxyMiddleware handles authentication. This guide covers per-request proxies, a reusable middleware, sticky sessions, country targeting, SOCKS5 and handling proxy errors in a crawl.
Updated 9 November 2026
Prerequisites
- Scrapy 2.13 or newer (
pip install scrapy). The examples use the asyncstart()method;start_requests()was deprecated in 2.13 and removed in 2.16. On older versions, renamestarttostart_requestsand dropasync. - A proxy login from the dashboard (Logins), shown here as
USERandPASS.
Crawl responsibly: collect public data, honour robots.txt where it applies, and keep request rates reasonable.
Basic HTTP proxy with request.meta
Set meta["proxy"] to the proxy URL. For HTTPS sites Scrapy opens a CONNECT tunnel, so TLS stays end to end. The proxy URL stays http:// for both HTTP and HTTPS targets.
import scrapy
class IpSpider(scrapy.Spider):
name = "ip"
async def start(self): # Scrapy 2.13+
yield scrapy.Request(
"https://api.ipify.org",
meta={"proxy": "http://USER-cc-us:PASS@gw.hyperproxy.io:8888"},
)
def parse(self, response):
self.logger.info("exit IP: %s", response.text)Authentication
Put the credentials in the proxy URL. HttpProxyMiddleware strips them out and sends them as a Proxy-Authorization header; when a later request uses a different proxy URL, the middleware replaces or removes that header so credentials don't leak between proxies. URL-encode the password if it contains reserved characters.
Scrapy also reads http_proxy and https_proxy environment variables, but a value in meta always wins, which makes per-request targeting possible.
A proxy middleware for the whole project
Rather than setting meta in every spider, add a small downloader middleware. It must have a lower order number than HttpProxyMiddleware (750) so it runs first.
# myproject/middlewares.py
from urllib.parse import quote
ENDPOINT = "gw.hyperproxy.io:8888"
class HyperproxyMiddleware:
"""Sets meta["proxy"] on every request that doesn't already have one."""
def __init__(self, user: str, password: str, options: str):
self.user, self.password, self.options = user, quote(password, safe=""), options
@classmethod
def from_crawler(cls, crawler):
s = crawler.settings
return cls(s["HYPERPROXY_USER"], s["HYPERPROXY_PASS"], s.get("HYPERPROXY_OPTIONS", ""))
def process_request(self, request):
if "proxy" in request.meta:
return None
username = self.user + self.options
# request.meta["sticky"] = "<id>" keeps one IP for a whole flow
if sticky := request.meta.get("sticky"):
username += f"-session-{sticky}-ttl-30"
request.meta["proxy"] = f"http://{username}:{self.password}@{ENDPOINT}"
return None# myproject/settings.py
import os
HYPERPROXY_USER = os.environ["HYPERPROXY_USER"]
HYPERPROXY_PASS = os.environ["HYPERPROXY_PASS"]
HYPERPROXY_OPTIONS = "-cc-us" # targeting, e.g. "-cc-de-city-berlin"
DOWNLOADER_MIDDLEWARES = {
# must run before HttpProxyMiddleware (750), which reads meta["proxy"]
"myproject.middlewares.HyperproxyMiddleware": 350,
}
CONCURRENT_REQUESTS = 16
CONCURRENT_REQUESTS_PER_DOMAIN = 4
DOWNLOAD_DELAY = 0.5
AUTOTHROTTLE_ENABLED = True
DOWNLOAD_TIMEOUT = 60Since Scrapy 2.14 middleware methods no longer take a spider argument. On older versions, write process_request(self, request, spider).
Rotating vs sticky IPs
The gateway gives each new connection a fresh exit. Scrapy keeps connections alive and reuses them, so with one proxy URL a crawl spreads over as many exits as it has open connections, not one per request. That is usually fine. When you need a new IP per request, or the same IP across several steps, use sessions: requests with the same session id share an exit for 5 minutes by default (up to 120 with ttl), and different ids get different exits.
import uuid
import scrapy
class AccountSpider(scrapy.Spider):
name = "account"
async def start(self):
sticky = uuid.uuid4().hex[:12] # letters and digits only
yield scrapy.Request("https://api.ipify.org", meta={"sticky": sticky})
def parse(self, response):
self.logger.info("step 1: %s", response.text)
# pass the same id on so the next step uses the same exit
yield response.follow(
"/?step=2", meta={"sticky": response.meta["sticky"]}, callback=self.step2
)
def step2(self, response):
self.logger.info("step 2: %s", response.text)Country and city targeting
Targeting goes into the username. With the middleware above, change HYPERPROXY_OPTIONS, or set meta["proxy"] directly for individual requests. All options are in Targeting.
| Options | Exit |
|---|---|
-cc-us | United States |
-cc-us-city-new_york | New York |
-cc-us-region-california | California |
-cc-de-asn-3320 | A specific German network |
-cont-eu | Anywhere in Europe |
-cc-us-city-houston-strict-false | Houston, or elsewhere in the US if none is available |
SOCKS5
The default Twisted download handler only speaks HTTP proxies, which work fine with the gateway. If you need SOCKS5, Scrapy 2.17 added SOCKS support to the experimental HttpxDownloadHandler. Check the download handlers docs for your version before relying on it.
# pip install "scrapy[httpx]" (Scrapy 2.17+)
# settings.py
DOWNLOAD_HANDLERS = {
"http": "scrapy.core.downloader.handlers._httpx.HttpxDownloadHandler",
"https": "scrapy.core.downloader.handlers._httpx.HttpxDownloadHandler",
}
# in the spider or middleware
meta = {"proxy": "socks5h://USER-cc-us:PASS@gw.hyperproxy.io:8888"}Concurrency
Scrapy is already concurrent. Tune CONCURRENT_REQUESTS and CONCURRENT_REQUESTS_PER_DOMAIN, and keep AUTOTHROTTLE_ENABLED on so Scrapy slows down when a site responds slowly. Proxies don't change what a polite crawl rate is for a site.
Error handling and retries
For HTTPS URLs, a gateway error arrives on the CONNECT request and Scrapy raises TunnelError with the status in the message, for example Could not open CONNECT tunnel with proxy gw.hyperproxy.io:8888 [{'status': 407, ...}]. For plain HTTP URLs you get a normal response with that status. See Errors.
- 407: credentials, an invalid option or no balance. Scrapy retries
TunnelErrorby default, but these retries will all fail, so stop the crawl and fix the cause. - 404: no exit matches the targeting. Widen it or add
strict-false. - 403: the target is not allowed. Don't retry.
- 429, 502, 504: retry.
RetryMiddlewaredoes this by default, and without a session each retry gets a new exit.
# settings.py: the default RETRY_HTTP_CODES already include 429, 502 and 504
RETRY_TIMES = 3
# spider: stop early on gateway errors that a retry can't fix
from scrapy.core.downloader.handlers.http11 import TunnelError
from scrapy.exceptions import CloseSpider
def errback(self, failure):
if failure.check(TunnelError):
msg = str(failure.value)
if "'status': 407" in msg:
self.logger.error("Proxy auth failed: check login, options and balance")
raise CloseSpider("proxy_auth")
elif "'status': 404" in msg:
self.logger.warning("No exit matches the targeting: %s", failure.request.url)Attach it with scrapy.Request(url, errback=self.errback).
Verify the exit IP
Run the basic spider with scrapy runspider ip_spider.py; it logs the IP that https://api.ipify.org sees. Add dont_filter=True if you request the same URL more than once, or Scrapy's duplicate filter will drop the repeats.
Troubleshooting
- The proxy isn't used: your middleware has an order number above 750, or it doesn't set
meta["proxy"]on retried or redirected requests (it should, since they pass through it again). - Every request shows the same few IPs: connection reuse; use per-request session ids as shown above.
- The spider yields no requests on Scrapy 2.16+: it still defines only
start_requests(). Rename it toasync def start(). - Unsupported proxy scheme:
socks5h://needs the httpx handler; usehttp://with the default handler.
FAQ
Do I need a rotating-proxy plugin for Scrapy?
No. The gateway does the rotation, so one proxy URL is enough. Plugins that rotate through a list of proxies aren't needed.
Can different spiders use different countries?
Yes. Set HYPERPROXY_OPTIONS in each spider's custom_settings, or set meta["proxy"] per request.
Does Scrapy send my credentials to the target site?
No. They go to the proxy in the CONNECT request or Proxy-Authorization header, not to the site.
What about JavaScript-heavy pages?
Render them with a browser instead: see the Playwright and Crawlee guides. For simple scripts, the Python requests guide may be enough. More snippets are in Examples.
Try it on your own workload
Sign up with GitHub or Google, create a proxy login and send your first request in a minute.
More proxy integration guides
- Python requests — Rotating and sticky residential proxies with Python requests, including SOCKS5 and retries.
- Python httpx — Sync and async httpx through a residential proxy with the proxy= argument and SOCKS5.
- Python aiohttp — High-concurrency aiohttp requests through rotating or sticky residential IPs.
- Playwright — Run Playwright through residential proxies, per browser or per context, with sticky sessions.
- Puppeteer — Launch Puppeteer behind an authenticated residential proxy with page.authenticate.
- Crawlee — Map Crawlee sessions to sticky residential IPs and target countries per request.
- Node.js axios — Send axios requests through HTTP and SOCKS5 residential proxies with proxy agents.
- Node.js fetch & undici — Use Node's built-in fetch with undici ProxyAgent or NODE_USE_ENV_PROXY.
- Go net/http — Configure Go's http.Transport for HTTP and SOCKS5 residential proxies.
- curl & SOCKS5 — Use curl with HTTP and SOCKS5 proxies, and test targeting from the command line.