Scraping and automation libraries

How to use a proxy with Scrapy

Scrapy is the Python framework for crawling many pages with concurrency, retries and pipelines built in. Proxy support comes from HttpProxyMiddleware, which is on by default: you put a proxy URL with credentials into request.meta and Scrapy adds the Proxy-Authorization header for you.

Below you will set a proxy on single requests, then on every request through a small downloader middleware, and then pin one IP per logged-in session with the cookiejar key.

Updated 23 November 2026

What you need
Hostgate.firstproxy.shop
HTTP / HTTPS port8000
SOCKS5 port9000
Usernameuser-country-gb
PasswordYOUR_TOKEN

Scrapy has no built-in SOCKS support, so use the HTTP port 8000. HTTPS sites are tunnelled through it. Your username and token appear on the Proxy setup page of your dashboard after your first order.

Setup

How do I connect Scrapy to a proxy?

Follow the steps in order. Replace YOUR_TOKEN with the token from your dashboard and change the country, city or session in the username to suit the job.

  1. Install Scrapy and create a project

    Scrapy 2.11 or later is assumed. The proxy features used here have been stable for many releases.

    python -m pip install scrapy
    scrapy startproject shop
    cd shop
    scrapy genspider prices example.com
  2. Set the proxy on a request

    Put the full proxy URL, credentials included, in meta["proxy"]. HttpProxyMiddleware reads it, strips the credentials and sends them as a Proxy-Authorization header. Do not set that header yourself: since Scrapy 2.6.2 it is removed when it does not match the proxy in meta.

    import scrapy
    
    PROXY = "http://user-country-gb:YOUR_TOKEN@gate.firstproxy.shop:8000"
    
    
    class IpSpider(scrapy.Spider):
        name = "ip"
    
        def start_requests(self):
            yield scrapy.Request("https://ipinfo.io/json", meta={"proxy": PROXY})
    
        def parse(self, response):
            yield response.json()
  3. Proxy every request with a downloader middleware

    A middleware sets the proxy in one place, including for requests that other code creates. Give it a priority lower than 750 so it runs before HttpProxyMiddleware.

    from urllib.parse import quote
    
    
    class FirstProxyMiddleware:
        def __init__(self, token, country):
            self.token = quote(token, safe="")
            self.country = country
    
        @classmethod
        def from_crawler(cls, crawler):
            s = crawler.settings
            return cls(s.get("FIRSTPROXY_TOKEN"), s.get("FIRSTPROXY_COUNTRY", "us"))
    
        def process_request(self, request, spider):
            if "proxy" in request.meta:
                return None
            country = request.meta.get("country", self.country)
            user = f"user-country-{country}"
            request.meta["proxy"] = f"http://{user}:{self.token}@gate.firstproxy.shop:8000"
            return None
  4. Target a city or change country per request

    Pass the targeting through meta and let the middleware build the username, or set meta["proxy"] directly for a one-off request. Cities use lowercase names with hyphens.

    yield scrapy.Request(
        "https://shop.example.com/de/item/4821",
        meta={"proxy": "http://user-country-de-city-munich:YOUR_TOKEN@gate.firstproxy.shop:8000"},
        callback=self.parse_item,
    )
  5. Keep one IP per session with cookiejar

    For logins or carts, combine a sticky session with Scrapy cookie jars. Each jar number gets its own session name, so each account keeps its own IP and its own cookies for up to 120 minutes on residential.

    def start_requests(self):
        for n in range(5):
            user = f"user-country-gb-session-acct{n}-ttl-30m"
            yield scrapy.Request(
                "https://shop.example.com/login",
                meta={
                    "cookiejar": n,
                    "proxy": f"http://{user}:YOUR_TOKEN@gate.firstproxy.shop:8000",
                },
                callback=self.login,
            )
    
    def login(self, response):
        # follow-up requests keep the same jar and proxy
        yield response.follow(
            "/account",
            meta={"cookiejar": response.meta["cookiejar"], "proxy": response.meta["proxy"]},
        )

    Rotating requests (no session part) are best for list and product pages. Keep sticky sessions for the flows that need them, so a single slow IP does not hold up the whole crawl.

Test

How do I check that the proxy works?

Run the spider from step 2 and look at the item in the log, or export it. The country should match the username.

A working proxy returns a response like the one shown, trimmed to the main fields. The IP belongs to the exit, the city and country follow your username, and the time zone is where that IP is located, here United Kingdom.

scrapy crawl ip -O ip.json
cat ip.json
ipinfo.io/json response
{
  "ip": "203.0.113.24",
  "city": "London",
  "country": "GB",
  "timezone": "Europe/London"
}

203.0.113.24 is a documentation address. Your result shows a real exit IP.

Targeting

How do I set country, city and session in the username?

All targeting is written into the username, so Scrapy needs no extra settings to change location. Parts are joined with hyphens in this order after your proxy user. The password is always your token.

Proxy username parts
PartFormatExampleRule
Country-country-{cc}-country-gbRequired. Two-letter country code in lowercase. 64 countries are available.
City-city-{city}-city-londonOptional. City name in lowercase, spaces become hyphens. 172 cities are available.
Session-session-{id}-session-a1b2c3Optional. Any letters and digits you choose. The same id keeps the same IP, a new id gets a new IP.
Session length-ttl-{minutes}m-ttl-30mUsed with a session. Residential 1 to 120 minutes, mobile 1 to 60, long-acting ISP up to 720 (12 hours).
Full usernameuser-country-gb-city-london-session-a1b2c3-ttl-30m

Find country codes and city values on the proxy locations page.

Troubleshooting

Scrapy proxy errors and fixes

The problems people run into most often with Scrapy, with the message you are likely to see and how to solve it.

407 responses that are not retried

407 is not in the default RETRY_HTTP_CODES, so Scrapy logs it and moves on. Fix the credentials rather than adding 407 to retries: copy the token again and percent-encode it with quote if it contains special characters.

Proxy-Authorization header disappears

Scrapy removes a manually set Proxy-Authorization header that does not belong to the proxy in meta. Put the credentials in the proxy URL and let HttpProxyMiddleware create the header.

TimeoutError or Twisted connection lost

The default DOWNLOAD_TIMEOUT is 180 seconds, which slows crawls when an exit is slow. Lower it to 30 to 60 and let RetryMiddleware send the request again on a new IP.

Requests skip the proxy

Check that the middleware path in DOWNLOADER_MIDDLEWARES matches your project name and that HTTPPROXY_ENABLED is not set to False. Requests created with a proxy meta of None go direct.

Blocks rise when concurrency goes up

Use AUTOTHROTTLE_ENABLED = True and a per-domain limit with CONCURRENT_REQUESTS_PER_DOMAIN. Rotating residential IPs spread load across addresses, but very fast bursts on one site still look automated.

FAQ

Scrapy proxy questions

Short answers to what people ask most about using a proxy with Scrapy.

How do I add a proxy to Scrapy?

Set request.meta["proxy"] to http://username:YOUR_TOKEN@gate.firstproxy.shop:8000. HttpProxyMiddleware is enabled by default and turns the credentials in the URL into a Proxy-Authorization header.

Does Scrapy support SOCKS5 proxies?

Not natively. Scrapy downloads over Twisted and only speaks HTTP proxies. Use the HTTP port, which also tunnels HTTPS sites, so SOCKS5 is not needed for crawling.

How do I rotate proxies in Scrapy?

With a rotating username the gateway changes the exit IP for you, so one proxy URL is enough. You do not need a list of proxies or a rotation middleware.

What priority should my proxy middleware have?

Any number below 750, the position of the built-in HttpProxyMiddleware, for example 350. Lower numbers run their process_request first.

Get your token and run the first Scrapy request

Create an account, top up from $40 with crypto, and copy the gateway, username and token from the dashboard.