How to Use a Proxy with Scrapy for Permitted Public Data
Learn how to route Scrapy spiders through a proxy for public data you are allowed to collect, using request meta, a downloader middleware and polite crawl settings.
10 min readUpdated Nov 13, 2026By XPASS Editorial Team

Scrapy is a mature Python framework for collecting structured data from web pages, and it is widely used for legitimate work such as price monitoring on public catalogues, aggregating open government datasets, archiving your own content, and checking your own sites for broken links. There are good reasons to add a proxy to such a project. You may need to see how a public page appears from a certain region, spread a polite crawl across a managed set of exit addresses, or keep crawler traffic separate from your office connection. This guide shows how to configure a proxy in Scrapy cleanly, and how to build the surrounding habits that keep a crawl lawful and considerate.
One framing point before the code. A proxy is a routing tool. It does not give you permission to collect anything, it does not override a site's terms of service, and it is not a way to defeat access controls, rate limits or CAPTCHAs. Everything below assumes you are collecting public data that you are allowed to collect, that you have read the site's terms and robots.txt, and that you follow the laws that apply to you and to the data.
What Scrapy does with a proxy
Scrapy ships with a downloader middleware called HttpProxyMiddleware. For each outgoing request it looks for a proxy in two places: the proxy key in request.meta, and the standard http_proxy, https_proxy and no_proxy environment variables, which it reads when the crawl starts. If it finds one, it sends the request to that proxy instead of the destination. For HTTPS targets the downloader asks the proxy to open a tunnel with CONNECT, then negotiates TLS with the real site through that tunnel, as described in the MDN overview of proxy servers and tunneling. The proxy sees the destination host name but not the encrypted page content.
If the proxy URL contains credentials, the middleware turns them into a Proxy-Authorization header for you. Scrapy's built-in support is for HTTP proxies. If your provider only offers SOCKS5, you usually put a small local HTTP-to-SOCKS bridge in front of it, or use a provider endpoint that speaks HTTP. Check the plan details on the proxy page for which protocols are included.

Three ways to set the proxy
There are three practical patterns, and they can be combined.
1. Per request, through meta. This is the most explicit and the best for small spiders:
import os
import scrapy
class CatalogueSpider(scrapy.Spider):
name = "catalogue"
start_urls = ["https://public-data.example.org/catalogue"]
def start_requests(self):
proxy = os.environ["CRAWL_PROXY_URL"] # e.g. http://user:pass@proxy.example.net:8080
for url in self.start_urls:
yield scrapy.Request(url, meta={"proxy": proxy})
def parse(self, response):
for row in response.css("table.items tr"):
yield {"name": row.css("td.name::text").get()}
next_page = response.css("a.next::attr(href)").get()
if next_page:
yield response.follow(next_page, meta=response.request.meta)
Notice the last line. Meta does not carry over automatically to the requests you create in callbacks, so you must pass it on. Forgetting this is a common cause of a spider that uses the proxy for the first page and then silently goes direct.
2. Environment variables. Set https_proxy and http_proxy in the shell or in your scheduler before launching scrapy crawl. This needs no code change and works well in containers, but it applies to the whole process, including any other HTTP calls it makes.
3. A downloader middleware. For anything beyond a toy spider, a small middleware centralizes the logic:
# middlewares.py
import os
class ProxyMiddleware:
def __init__(self, proxy_url):
self.proxy_url = proxy_url
@classmethod
def from_crawler(cls, crawler):
return cls(os.environ.get("CRAWL_PROXY_URL"))
def process_request(self, request, spider):
if self.proxy_url and "proxy" not in request.meta:
request.meta["proxy"] = self.proxy_url
# settings.py
DOWNLOADER_MIDDLEWARES = {
"myproject.middlewares.ProxyMiddleware": 350,
}
Give the middleware a priority number lower than the built-in HttpProxyMiddleware (which sits at 750) so that it sets the meta key before the built-in one reads it. Because the middleware reads the address from the environment, the same code runs unchanged on your laptop and on a server, and credentials never enter the repository.
Polite crawling settings
Using a proxy makes responsible crawl settings more important, not less, because it is easy to forget that a distant server pays for every request you make. A reasonable baseline in settings.py looks like this:
ROBOTSTXT_OBEY = True
USER_AGENT = "ExampleResearchBot/1.0 (+https://example.com/bot; contact@example.com)"
DOWNLOAD_DELAY = 2
CONCURRENT_REQUESTS_PER_DOMAIN = 2
AUTOTHROTTLE_ENABLED = True
AUTOTHROTTLE_START_DELAY = 2
AUTOTHROTTLE_MAX_DELAY = 30
RETRY_ENABLED = True
RETRY_TIMES = 2
HTTPCACHE_ENABLED = True
A few of these deserve comment:
ROBOTSTXT_OBEYmakes Scrapy fetch and honor the site'srobots.txt, which is the convention standardized in RFC 9309. It is advisory, not an access control, but ignoring it is a clear sign of an impolite crawler.- A descriptive
USER_AGENTwith a contact address lets a site operator reach you if your crawler causes a problem. Do not impersonate a normal browser or a search engine bot. AUTOTHROTTLE_ENABLEDadjusts delays based on how quickly the server answers, so the crawl slows down automatically when the site is under load.HTTPCACHE_ENABLEDstores responses on disk during development so that you do not repeat requests while you tune your selectors.
If the server returns 429 Too Many Requests or 503 Service Unavailable, treat it as an instruction to slow down, and honor any Retry-After header as described in RFC 9110. Do not respond by rotating addresses to push the same traffic through. If a site clearly blocks automated access, stop and look for an official API, a data export or a licensing route instead.
A quick calculation helps you pick these numbers on purpose instead of by feel. With a download delay of 2 seconds and 2 concurrent requests per domain, Scrapy fetches in the order of one page per second from that site at best, so about 3,600 pages an hour. In practice AutoThrottle and slow responses lower that figure. If a portal lists 10,000 notices, you should therefore expect a first crawl of several hours, not minutes. These figures are illustrative; the right pace depends on the site, and a stated limit in its terms always wins over your own settings. If the job is too slow for your deadline, ask the publisher for a bulk file rather than raising the rate.
A plain example: regional public notices
Imagine you maintain a dashboard of public tender notices that a government portal publishes in several languages, and the portal shows a slightly different page depending on the visitor's region. The terms of use allow automated reading of the public notices, and robots.txt does not block the listing pages. A responsible plan could look like this:
- Read the portal's terms and
robots.txtand write down what is allowed, the permitted paths and any stated request limit. - Create the spider with
ROBOTSTXT_OBEY = True, a descriptive user agent and a two-second delay. - Obtain a proxy endpoint with an exit in the region you want to observe, store its URL in
CRAWL_PROXY_URL, and add the middleware above. - Run a first crawl on three pages only, using
-s CLOSESPIDER_PAGECOUNT=3, and inspect the output and the log lines showing the proxy. - Verify that the page you received is the regional variant by checking a language or region marker in the HTML, then scale up carefully.
- Schedule the job at off-peak hours and store raw responses so you can re-parse them without requesting them again.
Once the three-page test looks right, review it against a short checklist before you scale up:
- The item fields are filled in and the text is not truncated or garbled.
- The log shows the expected status codes, with no run of 403, 429 or 503 responses.
- The exit address and region match what you meant to observe.
- The number of requests matches what you expected for three pages, with no hidden redirects or repeated fetches.
- The raw responses are cached on disk, so you can fix a selector and re-parse without downloading again.
If any line fails, fix it at three pages. A mistake discovered at ten thousand pages costs hours and puts needless load on the publisher.
Verifying that the proxy is really used
Before a long crawl, prove that traffic goes through the proxy. The simplest way is a tiny spider that requests an endpoint returning the caller's IP address, once with the proxy and once without, and compares the two. You can also run scrapy crawl with LOG_LEVEL = "DEBUG" and look at the downloader log lines, or set response.meta and response.request.meta["proxy"] into your item during testing. Record the exit address in your job log so that when a page looks different than expected, you can trace it to the exact exit used. If your provider documents the exit region, compare it with what the echo endpoint reports.
Limits and what to watch for
Meta propagation. Remember to carry the proxy forward in callbacks, or use the middleware so you do not have to.
Rotating versus sticky exits. A rotating endpoint can change the address between requests. That is fine for independent listing pages, but it breaks flows that depend on cookies or a login. Use a sticky or dedicated address for those flows if your provider offers it.
Concurrency limits. A plan may limit simultaneous connections. Scrapy's concurrency settings should stay below what the plan allows; check the plan page for what is included.
Latency. An extra hop adds delay. Raise
DOWNLOAD_TIMEOUTmoderately instead of retrying aggressively.Data protection. Public does not always mean without obligations. Personal data, even when visible on a public page, can be covered by privacy law. Collect only what you need, and store and share it responsibly.
JavaScript pages. Scrapy downloads HTML and does not run scripts. If a public page needs a browser to render, use a tool designed for that, such as the ones covered in using a proxy with Puppeteer, and keep the same politeness rules.
Failure handling. Log failed URLs and review them. Do not retry in a tight loop.
Scheduling. Run one crawl at a time per project. Two overlapping runs double the load on the site and are a common cause of accidental rate problems.
Cost of mistakes. Test on a handful of pages with
CLOSESPIDER_PAGECOUNTbefore any long run, and keep a log of each run's settings so you can reproduce it later.
Debugging checklist
If requests fail, test the proxy outside Scrapy first. The guide on sending an HTTP request through a proxy with cURL shows a quick way to confirm the host, port and credentials from the command line. If cURL works but Scrapy does not, check that the URL scheme in CRAWL_PROXY_URL is http://, that special characters in the password are percent-encoded, that your middleware priority is lower than 750, and that a stale no_proxy variable is not excluding your target. If only some requests use the proxy, look for callbacks that create requests without passing meta. When the same logic is needed in browser-based quality assurance, setting up a proxy in Selenium follows a very similar checklist.
Summary
Scrapy supports proxies through the proxy key in request meta, the standard environment variables, or a small downloader middleware that applies one address to every request. Keep credentials in environment variables, give your middleware a lower priority number than the built-in one, and verify the exit address before a long run. A proxy is never a substitute for permission: keep ROBOTSTXT_OBEY on, identify your crawler, throttle by default, respect 429 and 503 responses, and collect only public data you are allowed to use. When you are ready to choose an endpoint, the details of what is included are on the proxy page.
Frequently asked questions
How do I make a Scrapy request go through a proxy?
Set the proxy key in the request meta, for example meta={'proxy': 'http://host:port'}. Scrapy's built-in HttpProxyMiddleware then uses it for that request. You can also set the http_proxy and https_proxy environment variables before starting the crawl, or write a small downloader middleware that assigns the proxy to every request.
Can Scrapy use a proxy that needs a username and password?
Yes. Put the credentials in the proxy URL, such as http://user:password@host:port, and the built-in middleware converts them into a Proxy-Authorization header. Read the values from environment variables so they are not stored in your code.
Does a proxy let me ignore robots.txt or site rules?
No. A proxy only changes the network route. Keep ROBOTSTXT_OBEY enabled, read the site's terms, and collect only data you are permitted to collect. If a site asks crawlers to stay away, respect that.
How do I keep a Scrapy crawl polite?
Use a clear user agent with contact details, set DOWNLOAD_DELAY or enable AutoThrottle, limit concurrent requests per domain, handle 429 and 503 responses by slowing down, and cache responses so you do not request the same page twice.
References
About the author

Bob Kanokphon Thongdee
- Founder of XPASS VPN
- Co-founder of eSIMonline.asia
- More than 7 years in online marketing
- Founder of Cojourney Visa and Cojourney Travel
Need a proxy for this?
XPASS Proxy sells residential proxy traffic by the gigabyte, with the price shown before you pay.
See proxy plansKeep reading

Proxy Guides
How to Set Up a Proxy in Selenium for QA Work
A practical guide to routing Selenium WebDriver sessions through a proxy for regional and environment testing, with Chrome and Firefox examples and a verification routine.
9 min read

Proxy Guides
How to Send an HTTP Request Through a Proxy with cURL
Use cURL to test an HTTP or SOCKS5 proxy from the command line: the right flags, authentication, environment variables, a verification routine and how to read errors.
9 min read

Proxy Guides
How to Use a Proxy with Puppeteer in Node.js
A step-by-step guide to routing Puppeteer through a proxy in Node.js, including authentication, excluding hosts, verifying the IP and avoiding common mistakes.
9 min read