Code and command line
Scrapy proxy setup
Scrapy already ships with HttpProxyMiddleware, which reads a proxy URL from each request and turns the login and password in it into the right header. That means the whole integration can be a single line in a spider, or a few lines of middleware when you want every request routed the same way.
This guide covers both, then shows how to keep a multi-page crawl on one address with a session login and how to tune concurrency for a gateway rather than a single server.
What do you need before adding a proxy in Scrapy?
Tick these off before the first step. Your login and password appear in your account once the first top-up of $40 or more has been credited.
| Requirement | Detail |
|---|---|
| Scrapy 2.8 or newer | Older releases handle proxy credentials less cleanly when they change between requests. |
| A project | Created with scrapy startproject, or a single spider file run with scrapy runspider. |
| TopProxy login and password | For example tp7k2m9_country-us with your own password. |
| HttpProxyMiddleware enabled | It is on by default. Only check this if you changed DOWNLOADER_MIDDLEWARES. |
Where do the proxy host, port and login go in Scrapy?
Work through the steps in order. Swap YOUR_PASSWORD for your proxy password and tp7k2m9 for your account name.
Route one request through the gateway
Put the full proxy URL, including login and password, in
meta["proxy"]. Scrapy removes the credentials from the URL and sends them as a Proxy-Authorization header, so you do not build that header yourself.import scrapy PROXY = "http://tp7k2m9_country-us:YOUR_PASSWORD@proxy.topproxy.shop:8080" 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()Move the proxy into a downloader middleware
Repeating the meta key in every spider is easy to forget. A middleware sets it on any request that does not already have one. It also reads optional
country,cityandsessionvalues from the request meta, so a spider can ask for a location without knowing the login format.import os from urllib.parse import quote class TopProxyMiddleware: host = "proxy.topproxy.shop:8080" def __init__(self): self.password = quote(os.environ.get("TOPPROXY_PASSWORD", "YOUR_PASSWORD"), safe="") def process_request(self, request, spider): if "proxy" in request.meta: return None m = request.meta login = "tp7k2m9_country-" + m.get("country", "us") if m.get("city"): login += "_city-" + m["city"] if m.get("session"): login += "_session-" + m["session"] + "_life-" + str(m.get("life", 30)) request.meta["proxy"] = f"http://{login}:{self.password}@{self.host}" return NoneTip.The priority 350 runs this middleware before the built-in HttpProxyMiddleware at 750, which then turns the credentials into the header.
Tune throttling for a rotating gateway
Each request may leave from a different address, so per-IP limits on the target matter less than the total pace you send. AutoThrottle adjusts the delay from response times, and a moderate per-domain concurrency keeps the target comfortable.
AUTOTHROTTLE_ENABLED = True AUTOTHROTTLE_TARGET_CONCURRENCY = 4 CONCURRENT_REQUESTS_PER_DOMAIN = 8 RETRY_TIMES = 3 RETRY_HTTP_CODES = [429, 500, 502, 503, 504, 522, 524, 408] DOWNLOAD_TIMEOUT = 40Run the crawl and log the exits
Run the spider and export the results. Each item from the ipinfo spider shows the exit address, so a short run is enough to see rotation happening.
export TOPPROXY_PASSWORD="your-password" scrapy crawl ip -O exits.json
How can you confirm the proxy is active in Scrapy?
Open scrapy shell with a proxied request and read the JSON. If the country field matches the login, every request your middleware touches is going through TopProxy.
scrapy shell
>>> from scrapy import Request
>>> fetch(Request("https://ipinfo.io/json", meta={"proxy": "http://tp7k2m9_country-us:YOUR_PASSWORD@proxy.topproxy.shop:8080"}))
>>> response.json()["country"]The response shown here is shortened to the fields that matter. The region and time zone follow the exit, in this case France.
{
"ip": "198.51.100.47",
"city": "Lyon",
"region": "Auvergne-Rhone-Alpes",
"country": "FR",
"timezone": "Europe/Paris"
}198.51.100.47 is an address reserved for documentation. A live check prints a real exit.
How do you switch between rotating and held IPs in Scrapy?
Without a session value the middleware sends a rotating login. For flows that must stay on one address, such as a paginated listing behind a cookie, give those requests the same session value. Use a fresh value per item or per category so one blocked address does not stall the whole crawl.
yield scrapy.Request(url, meta={"country": "us"})How the login is put together
Every setting lives in the login, joined with underscores. Nothing else in Scrapy changes when you switch location or session.
| Part | Meaning | Rule |
|---|---|---|
| tp7k2m9 | Your account name | Always first. Yours is shown in your account and replaces tp7k2m9 in every example here. |
| _country-us | Exit country | Two-letter code in lowercase. 64 countries to choose from. |
| _city-new-york | Exit city, optional | Lowercase, spaces become hyphens. 172 cities in total. |
| _session-a1b2c3 | Session name, optional | Letters and digits you pick. Same name, same exit. New name, new exit. |
| _life-30 | Session life in minutes | Only with a session. Residential 1 to 120 minutes, mobile 1 to 60 minutes, long session ISP up to 12 hours (life 720). |
All parts togethertp7k2m9_country-us_city-new-york_session-a1b2c3_life-30
How do you choose an exit country or city in Scrapy?
Pass the country and, if needed, the city in meta. The middleware builds the login, for example tp7k2m9_country-fr_city-lyon.
yield scrapy.Request(url, meta={"country": "fr"})Codes and city values for all 64 countries are listed on the proxy locations pages.
How do you fix a 407 or connection error in Scrapy?
Find the line that matches what you see. Most problems come down to the login, the port or the network you are on.
| Symptom | Likely cause | Fix |
|---|---|---|
Log shows 407 on CONNECT | The password contains a symbol that broke the URL, or the login is wrong. | Percent-encode the password with quote() as in the middleware and check the login. |
| Requests bypass the proxy | A custom DOWNLOADER_MIDDLEWARES dict disabled HttpProxyMiddleware. | Remove the None entry for scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware. |
TCP connection timed out in bursts | Concurrency is far above what the target accepts. | Lower CONCURRENT_REQUESTS_PER_DOMAIN and keep AutoThrottle on. |
Many 403 answers on one domain | The site blocks hosting networks or reads a missing browser header set. | Use residential or mobile exits and send realistic headers. |
Still stuck? Run the same login through the cURL check. If cURL connects, the issue is in the Scrapy settings. If it does not, write to support with the error text.
What kind of proxy pairs well with Scrapy?
All products sit behind the same gateway and share one prepaid balance, so moving from one to another means buying the other product and changing the login, nothing more.
- Rotating Residential ProxiesBroad household pool for large crawls across many domains.$0.23 per GB
- Long Session ISP ProxiesKeeps one ISP address for hours, handy for crawls that page through a logged-in listing.$0.13 per GB
- Datacenter Proxy PoolLow cost per IP for wide crawls of sites with light protection.$0.58 per 100 IPs per month
Calling pages from code at scale? The TopProxy API docs cover the Scraping API, which renders pages and retries on its own.
What else do Scrapy users ask about proxies?
Can Scrapy talk to the SOCKS5 port?
Not with its built-in downloader. Use the HTTP port 8080, which covers both http and https targets. If a project truly needs SOCKS5, a local converter that exposes an HTTP proxy is the usual workaround.
Do I need a third-party rotating proxy package?
No. TopProxy rotates on the gateway side, so a single login already gives different exits. Packages that cycle through proxy lists are only useful when you hold a list of fixed IPs.
How do I change the login per request?
Set a different meta proxy URL, or different meta values with the middleware above. Recent Scrapy releases update the Proxy-Authorization header when the credentials in meta change.
Should I use the Scraping API instead?
If pages need JavaScript rendering or the site blocks most plain clients, the Scraping API handles rendering and retries for you and returns the page. For static HTML, Scrapy with proxies is cheaper per page.
Does this work with scrapy-playwright?
Yes, but the browser takes its proxy from the Playwright launch options, not from request meta. Set the proxy server, username and password in PLAYWRIGHT_LAUNCH_OPTIONS.
Related setup guides
- Python RequestsA proxies dictionary, a Session with retries, SOCKS5 through PySocks and a pool of sticky logins.
- PlaywrightProxy server, username and password at launch or per context, in Node.js and Python, with one location per context.
- cURLOne terminal command to prove your login works, then SOCKS5 with remote DNS and a reusable config file.
- SeleniumChrome cannot take a proxy password from a flag. Two working routes: a small auth extension, or Selenium Wire.
Ready to connect Scrapy?
Open an account, add $40 or more in crypto, and your login and password are waiting in the account area.