Integrations

Scrapy proxies: meta proxy and rotation middleware

Use proxies in Scrapy: set meta['proxy'] with credentials in the URL, rotate through a list with a small downloader middleware and keep crawls polite.

3 min read Updated

On this page

Scrapy supports proxies out of the box. Its built-in HttpProxyMiddleware, enabled by default, reads the proxy URL from each request's meta, takes the username and password from that URL and sends them to the proxy. You don't need extra packages for HTTP proxies.

One proxy for a request

import scrapy


class IpSpider(scrapy.Spider):
    name = "ip"

    async def start(self):
        yield scrapy.Request(
            "https://api.ipify.org?format=json",
            meta={"proxy": "http://USERNAME:PASSWORD@HOST:PORT"},
        )

    def parse(self, response):
        yield {"ip": response.json()["ip"]}

async def start() is the entry point from Scrapy 2.13. On older versions, name the method def start_requests(self) and keep the same body.

Use http:// in the proxy URL for both HTTP and HTTPS websites; Scrapy opens a tunnel through the proxy for HTTPS pages. If your password contains characters such as @ or #, percent-encode them in the URL.

One proxy for the whole crawl

HttpProxyMiddleware also reads the standard environment variables, which is the quickest way to send a whole crawl through a rotating line:

export https_proxy="http://USERNAME:PASSWORD@HOST:PORT"
export http_proxy="http://USERNAME:PASSWORD@HOST:PORT"
scrapy crawl ip

A proxy value in meta takes precedence over the environment variables.

Rotating through a list with a middleware

A rotating line from the generator changes IP by itself, so a single URL is enough for most crawls. A list helps when you use several sticky lines or static IPs and want to spread requests across them.

middlewares.py:

import random


class ProxyListMiddleware:
    """Gives every request a proxy from the PROXY_LIST setting."""

    def __init__(self, proxies):
        self.proxies = proxies

    @classmethod
    def from_crawler(cls, crawler):
        proxies = crawler.settings.getlist("PROXY_LIST")
        if not proxies:
            raise ValueError("PROXY_LIST is empty")
        return cls(proxies)

    def process_request(self, request, spider=None):
        # Keep a proxy that was set on purpose, but pick a new one on retries.
        if "proxy" not in request.meta or request.meta.get("retry_times"):
            request.meta["proxy"] = random.choice(self.proxies)

settings.py:

DOWNLOADER_MIDDLEWARES = {
    "myproject.middlewares.ProxyListMiddleware": 350,
}

PROXY_LIST = [
    "http://USERNAME:PASSWORD@HOST:PORT",
    # one line per sticky session or static IP from your dashboard
]

Replace myproject with your project's package name. The order value 350 runs this middleware before the built-in HttpProxyMiddleware at 750, which then adds the credentials. The spider=None parameter keeps the method working on both older and newer Scrapy versions, which differ in whether they pass the spider.

The middleware stops with an error on an empty list on purpose: a crawl that silently runs without a proxy would expose your own IP.

Keeping one IP for a sequence of pages

Some flows need the same IP from one page to the next, for example pagination that keeps state on the server. Pass the proxy along with each follow-up request:

    def parse(self, response):
        for href in response.css("a.next::attr(href)").getall():
            yield response.follow(href, self.parse, meta={"proxy": response.meta["proxy"]})

Use a sticky line for this. Rotating vs sticky sessions explains what a sticky session holds and what to do when it ends.

Polite, stable settings

ROBOTSTXT_OBEY = True
CONCURRENT_REQUESTS_PER_DOMAIN = 4
DOWNLOAD_DELAY = 0.5
AUTOTHROTTLE_ENABLED = True
DOWNLOAD_TIMEOUT = 30
RETRY_TIMES = 2

AutoThrottle adjusts the delay to how fast the site responds. Retries cover timeouts and responses such as 429 and 503, and with the middleware above each retry goes out through another proxy from the list. If the log shows a tunnel error with status 407, the credentials are wrong, and retrying won't fix them. Check what a site allows with the robots.txt checker and read its terms before you crawl it. The web scraping use case covers planning a larger crawl.

SOCKS5

Scrapy's default download handler supports HTTP proxies only. Scrapy 2.15 added an experimental download handler based on httpx that can use SOCKS5 proxies, but the Scrapy docs don't recommend it for production yet. With FreshProxies, the simplest path is the HTTP endpoint, which works with every Scrapy feature.

For one-off scripts outside Scrapy, see the Python guide.