Using a proxy with Scrapy: authenticated setup, polite throttling, error fixes and rotating between runs
In this article
Scrapy supports proxies out of the box: set request.meta["proxy"] (or the http_proxy and https_proxy environment variables) to http://USER:PASS@HOST:PORT and its built-in HttpProxyMiddleware handles the login. The documentation is just scattered, so this guide gathers what you need: two ways to add an authenticated proxy, including a complete proxy middleware, a "polite" throttling setup that lowers the chance of getting blocked, how to check the proxy is in use, the usual errors, and how to rotate a 4G proxy's IP without breaking a run.
How Scrapy uses a proxy
Scrapy ships with HttpProxyMiddleware, enabled by default. It takes the proxy from two places:
- the environment variables
http_proxyandhttps_proxy, read once when Scrapy starts, - each request's
request.meta["proxy"], which takes priority over the environment.
The username and password go straight into the proxy address (http://USER:PASS@HOST:PORT). Scrapy splits them out and sends the proxy an authentication header.
Note: Scrapy only supports HTTP/HTTPS proxies, not SOCKS5. With 65Proxy, use the HTTP connection details. The difference between the two is in SOCKS5 vs HTTP proxies.
Way 1: environment variables
The quickest way, applying to every request. Both variables start with http://, even https_proxy, because Scrapy talks to the proxy over HTTP:
export https_proxy="http://USER:PASS@HOST:PORT"
export http_proxy="$https_proxy"
scrapy crawl prices -O prices.jsonOn Windows PowerShell:
$env:HTTPS_PROXY = "http://USER:PASS@HOST:PORT"
$env:HTTP_PROXY = $env:HTTPS_PROXY
scrapy crawl prices -O prices.jsonWay 2: a Scrapy proxy middleware
When you want control in code (only some domains through the proxy, another proxy for a few requests, or a clear error when the proxy isn't set), write a small downloader middleware that sets request.meta["proxy"]. Scrapy's built-in HttpProxyMiddleware does the rest: it takes the username and password out of that URL and sends them to the proxy as a Proxy-Authorization header.
1. The middleware. In myproject/middlewares.py:
import os
from urllib.parse import urlparse
class AuthProxyMiddleware:
"""Send requests through one HTTP proxy with a username and password."""
def __init__(self, proxy_url, domains):
self.proxy_url = proxy_url # http://USER:PASS@HOST:PORT
self.domains = domains # empty list = every request
@classmethod
def from_crawler(cls, crawler):
proxy_url = os.environ.get("PROXY_URL")
if not proxy_url:
# Stop here rather than crawl from your own IP by mistake.
raise RuntimeError("Set PROXY_URL to http://USER:PASS@HOST:PORT")
return cls(proxy_url, crawler.settings.getlist("PROXY_DOMAINS"))
def process_request(self, request, spider=None):
if "proxy" in request.meta:
return None # this request chose its own proxy
host = urlparse(request.url).hostname or ""
if self.domains and not any(
host == d or host.endswith("." + d) for d in self.domains
):
return None # not a domain we send through the proxy
request.meta["proxy"] = self.proxy_url
return None2. Enable it in settings.py. Downloader middlewares see each request in increasing order of their number, and HttpProxyMiddleware sits at 750, so give yours a lower number:
DOWNLOADER_MIDDLEWARES = {
"myproject.middlewares.AuthProxyMiddleware": 740,
}
PROXY_DOMAINS = [] # e.g. ["example.sg"]; empty = proxy every requestReplace myproject with your project's name. Leave HttpProxyMiddleware enabled (don't set it to None): it's the part that turns USER:PASS in the URL into the authentication header.
3. Run it. Pass the proxy in an environment variable, so the username and password stay out of your code and settings:
export PROXY_URL="http://USER:PASS@HOST:PORT"
scrapy crawl prices -O prices.jsonOn Windows PowerShell, set it with $env:PROXY_URL = "http://USER:PASS@HOST:PORT", then run the same scrapy crawl line. When the crawl starts, Scrapy's log lists the enabled downloader middlewares; AuthProxyMiddleware should be among them.
Details worth knowing:
- Special characters in the password must be percent-encoded in
PROXY_URL(@becomes%40,:becomes%3A). Scrapy decodes them before sending. - One request through a different proxy: set it on that request, for example
scrapy.Request(url, meta={"proxy": "http://USER2:PASS2@HOST2:PORT2"}). The middleware leaves requests that already havemeta["proxy"]alone. - Don't mix both ways.
meta["proxy"]takes priority overhttp_proxyandhttps_proxy, but requests the middleware skips would still use the environment proxy if you also exported it as in Way 1. - Changing the IP is done with the proxy's rotation link, outside the crawl: see rotating between runs.
Polite throttling
With a 4G proxy, every request goes out from one IP, so pace matters more than ever. A sensible starting point for settings.py:
ROBOTSTXT_OBEY = True
USER_AGENT = "my-crawler/1.0 (+mailto:[email protected])"
CONCURRENT_REQUESTS_PER_DOMAIN = 2
DOWNLOAD_DELAY = 2 # seconds; Scrapy varies it 0.5–1.5x
DOWNLOAD_TIMEOUT = 30 # the 180-second default is too long
AUTOTHROTTLE_ENABLED = True
AUTOTHROTTLE_START_DELAY = 2
AUTOTHROTTLE_MAX_DELAY = 60
AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
RETRY_TIMES = 3
RETRY_HTTP_CODES = [500, 502, 503, 504, 522, 524, 408, 429]
HTTPCACHE_ENABLED = True # while developing: don't re-download pages- AutoThrottle slows down automatically when the site responds slowly.
- The default retry middleware doesn't wait per
Retry-After. If you see 429s often, raiseDOWNLOAD_DELAYand lowerCONCURRENT_REQUESTS_PER_DOMAINrather than adding retries. What each error code means is in 403, 429 and 503 errors when scraping. - The HTTP cache while developing lets you fix your parsing code without hitting the target again. Turn it off for real runs if you need fresh data.
Check the proxy is in use
scrapy fetch downloads a page with the current settings and prints it:
scrapy fetch --nolog https://api.ipify.orgThe result should be the proxy's IP, not your home IP. To see the network and country as well:
scrapy fetch --nolog https://ipinfo.io/jsonRotating between runs
With a 4G proxy, rotating means calling the proxy's rotation link and waiting for the device to reconnect. In Scrapy, the cleanest approach is to rotate between runs, not between requests:
- rotating mid-run leaves cookies and sessions out of step with the IP,
- in-flight requests fail while the device reconnects,
- and each 65Proxy proxy rotates at most once every 5 minutes.
A script to run before each crawl (the rotation link lives in the ROTATE_URL environment variable):
export https_proxy="http://USER:PASS@HOST:PORT"
export http_proxy="$https_proxy"
old=$(curl -s -m 15 -x "$https_proxy" https://api.ipify.org)
curl -s -m 60 "$ROTATE_URL" > /dev/null
for i in $(seq 1 20); do
sleep 3
new=$(curl -s -m 10 -x "$https_proxy" https://api.ipify.org)
if [ -n "$new" ] && [ "$new" != "$old" ]; then break; fi
done
echo "IP: $old -> $new"
scrapy crawl prices -O prices.jsonThe same in Python, which also runs on Windows and works with the middleware above: it rotates, waits for the new IP, then starts the crawl. Save it as run_crawl.py next to scrapy.cfg and run python run_crawl.py with PROXY_URL and ROTATE_URL set:
import os
import time
import urllib.request
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings
PROXY_URL = os.environ["PROXY_URL"] # http://USER:PASS@HOST:PORT
ROTATE_URL = os.environ["ROTATE_URL"] # the proxy's rotation link
# Call the rotation link directly; check the IP through the proxy.
direct = urllib.request.build_opener(urllib.request.ProxyHandler({}))
via_proxy = urllib.request.build_opener(
urllib.request.ProxyHandler({"http": PROXY_URL, "https": PROXY_URL})
)
def proxy_ip():
try:
return via_proxy.open("https://api.ipify.org", timeout=15).read().decode()
except OSError:
return None # the device is still reconnecting
old_ip = proxy_ip()
try:
direct.open(ROTATE_URL, timeout=60).read()
except OSError as err:
raise SystemExit(f"Rotation failed: {err}")
for _ in range(20):
time.sleep(3)
new_ip = proxy_ip()
if new_ip and new_ip != old_ip:
break
else:
raise SystemExit("The IP did not change. Was the last rotation under 5 minutes ago?")
print(f"IP: {old_ip} -> {new_ip}")
settings = get_project_settings()
settings.set("FEEDS", {"prices.json": {"format": "json", "overwrite": True}})
process = CrawlerProcess(settings)
process.crawl("prices")
process.start()The rotation link is called without the proxy, so the call doesn't depend on the connection it's about to reset. More versions of the wait loop (curl, Python, Node.js) are in rotating proxy IPs via API.
Common errors
- 407 Proxy Authentication Required: wrong username or password. If the password has special characters, encode them in the proxy address:
@becomes%40,:becomes%3A. - TunnelError: Could not open CONNECT tunnel. The proxy refused to open a tunnel for HTTPS; usually wrong credentials, the wrong port, or a SOCKS5 port by mistake.
- Errors with
socks5://: Scrapy doesn't support SOCKS; switch to the HTTP port. - A burst of timeouts: usually while the proxy is rotating or signal is weak; sensible
RETRY_TIMESandDOWNLOAD_TIMEOUThandle it. - The IP is still your home IP: the environment variable was set after Scrapy started, or in a different terminal window.
General proxy errors are covered in common proxy errors.
65Proxy's Singapore 4G proxies for Scrapy
Our proxies have an HTTP port with a username and password (exactly what Scrapy needs) plus an on-demand rotation link (at most once every 5 minutes). Singapore mobile-carrier IPs help you reach public data on sites that block server IPs, or data shown only to Singapore visitors. Priced 1 day $4, 7 days $13, 1 month $32 (200GB each), plus monthly plans with more bandwidth (500GB $40, 1TB $65). Use them with the throttling setup above and respect each site's rules. See is web scraping legal and pricing.
Frequently asked questions
Is one 4G proxy enough for Scrapy?
For polite scraping (a few requests a second or fewer per site), it usually is. If you need much more speed, ask the target site about an API before thinking about more IPs.
Is there a rotating-proxy middleware for Scrapy?
There are libraries that cycle through a list of proxies. With a 4G proxy that rotates by link you don't need them. Just rotate between runs as above.
Can Scrapy run JavaScript?
Scrapy itself can't. For pages that need JavaScript, look for the API the page calls, or use a headless browser. See scraping JavaScript sites.