01Per request
Scrapy's built-in HttpProxyMiddleware reads request.meta["proxy"]. A login inside the URL is turned into the right header for you.
import scrapy
PROXY = "http://USERNAME:PASSWORD@dc.fullstackproxy.com:38417"
class Catalog(scrapy.Spider):
name = "catalog"
async def start(self):
for n in range(1, 51):
yield scrapy.Request(f"https://example.com/page/{n}", meta={"proxy": PROXY})
def parse(self, response):
yield {"url": response.url, "title": response.css("title::text").get()}02For every request
A tiny downloader middleware sets the proxy on everything, including requests made from parse:
# middlewares.py
class GatewayProxy:
def __init__(self, proxy):
self.proxy = proxy
@classmethod
def from_crawler(cls, crawler):
return cls(crawler.settings["GATEWAY_PROXY"])
def process_request(self, request):
request.meta.setdefault("proxy", self.proxy)
# settings.py
GATEWAY_PROXY = "http://USERNAME-country-us:PASSWORD@gw.fullstackproxy.com:47631"
DOWNLOADER_MIDDLEWARES = {
"myproject.middlewares.GatewayProxy": 350, # before HttpProxyMiddleware (750)
}03Sticky sessions per item
Scrapy keeps connections alive, so a run of requests may share an IP anyway. When a sequence must come from one address, such as a listing and its detail pages, make it explicit with a session name tied to the item:
def proxy_for(key):
return f"http://USERNAME-country-us-session-{key}-lifetime-30:PASSWORD@gw.fullstackproxy.com:47631"
def parse(self, response):
for href in response.css("a.product::attr(href)").getall():
key = href.rstrip("/").split("/")[-1][:25].replace("-", "_")
yield response.follow(href, self.parse_item, meta={"proxy": proxy_for(key)})04Settings that matter
The samples use the current Scrapy API: async def start() in spiders and middleware methods without a spider argument. On older versions, write def start_requests(self) instead of start, and give process_request a spider argument after request.
CONCURRENT_REQUESTS: how many requests are in flight. Start at 16 to 32 and raise it while responses stay healthy.RETRY_HTTP_CODES: add429and502. On a rotating login a retry leaves from a new IP.DOWNLOAD_TIMEOUT: 30 seconds is plenty for most pages through a proxy.AUTOTHROTTLE_ENABLED = True: lets Scrapy slow down when the target does.
Scrapy does not speak SOCKS5 on its own. The gateway serves HTTP on the same port, so use the http:// form.