Scrapy Proxy: Rotating Proxies for Scrapy Middleware
Integrate RotatingProxy into your Scrapy spider using HTTP or SOCKS5 to route requests through rotating residential, mobile, datacenter, or ISP IPs. You control geo-targeting and session stickiness by encoding options directly into the proxy username.
- Use the meta proxy middleware to pass proxy credentials and options per request.
- Enable sticky sessions for a domain by setting a session ID in the request meta.
- Target specific countries, US states, or cities by adding options to the proxy username.
- Handle common proxy errors like 407 and timeouts with retry middleware.
Scrapy Proxy Setup Overview
To use RotatingProxy with Scrapy, you configure your spider or settings to route HTTP and HTTPS requests through our gateway at gw.rotatingproxy.cc on port 7070 (HTTP CONNECT) or port 7071 (SOCKS5). Authentication, network selection, geo-targeting, and session control are all passed via the proxy username. This guide covers the standard HTTP proxy setup, the optional SOCKS5 support, and how to implement advanced patterns like sticky sessions per domain for scraping tasks like price monitoring or rank tracking.
Where to Configure Proxy Settings in Scrapy
Scrapy's proxy configuration lives in the request meta dictionary or in custom downloader middleware. The most flexible method is to set the proxy meta key for each request, which allows you to change the proxy user, network, or location on the fly. For a global proxy applied to all requests, you can write a simple downloader middleware that adds the proxy URL to every request. We recommend the per-request approach for managing sessions and choosing proxy locations dynamically based on the target site.
HTTP Proxy Setup on Port 7070
Construct a proxy URL in the format http://USERNAME:PASSWORD@gw.rotatingproxy.cc:7070 and assign it to request.meta['proxy']. Replace USERNAME with your proxy user's login plus any options like net.res_cc.us. Here is a basic spider example that uses a rotating residential IP from the United States for all its requests.
import scrapy
class ExampleSpider(scrapy.Spider):
name = 'example'
start_urls = ['https://api.ipify.org?format=json']
def start_requests(self):
proxy_user = 'YOUR_LOGIN_net.res_cc.us' # Your proxy user login
proxy_pass = 'YOUR_PASSWORD'
proxy_url = f'http://{proxy_user}:{proxy_pass}@gw.rotatingproxy.cc:7070'
for url in self.start_urls:
yield scrapy.Request(url, callback=self.parse, meta={'proxy': proxy_url})
def parse(self, response):
self.logger.info(f'Exit IP: {response.text}')
This setup will give each new connection a fresh residential IP from the US. For HTTPS sites, Scrapy and the underlying library will use the CONNECT method automatically through the same proxy URL. This is the standard method for most Python requests-based tools.
SOCKS5 Proxy Support on Port 7071
Scrapy does not natively support SOCKS5 proxies in its core. If your project requires SOCKS5, you must install an additional library like scrapy-socks or use a SOCKS-to-HTTP bridge locally. Given the extra complexity, we recommend using the HTTP port 7070 for Scrapy projects. The functionality is identical; both ports support authentication, targeting, and sessions. Use SOCKS5 only if you have a specific toolchain requirement.
Passing Targeting and Session Options in the Username
All proxy configuration beyond the login is done via underscores in the username. You specify the network, country, state, city, and session ID there. For example, to target Chicago with a sticky session for 30 minutes, you would build a username like LOGIN_net.res_cc.us_city.chicago_sid.abc123_ttl.30. In your spider, you can generate these usernames dynamically per request or per domain. This example spider uses a different sticky session for each start URL domain.
import scrapy
from urllib.parse import urlparse
class SessionSpider(scrapy.Spider):
name = 'session_spider'
def start_requests(self):
sites = ['https://example.com', 'https://anotherexample.org']
for url in sites:
domain = urlparse(url).netloc
# Create a session ID based on domain
session_id = domain.replace('.', '')[:12]
proxy_user = f'LOGIN_net.res_sid.{session_id}_ttl.15'
proxy_url = f'http://{proxy_user}:PASSWORD@gw.rotatingproxy.cc:7070'
yield scrapy.Request(url, callback=self.parse, meta={'proxy': proxy_url, 'session_domain': domain})
def parse(self, response):
# Subsequent requests to the same domain reuse the same IP for 15 minutes
pass
This pattern is essential for tasks like social media management or ecommerce data collection where you need to maintain a consistent IP per site. Remember, the sid value must be 6 to 16 lowercase letters or digits.
Verifying the Exit IP and Location
You can make a test request to a service like https://api.ipify.org?format=json or https://ipinfo.io/json at the start of your crawl. Log the response in your parse method. For more detailed checks, see our list of checking the exit IP and location tools. This step confirms your geo-targeting options like cc.de or city.berlin are effective.
Common Proxy Errors and Fixes
You may encounter a few common errors when using proxies with Scrapy.
- 407 Proxy Authentication Required: This means the proxy rejected your credentials. Check that the username and password in the proxy URL are correct, and ensure the proxy user is active and has permission for the network you selected (e.g.,
net.res). - Timeouts: If requests are timing out, the target site may be slow, or the proxy exit node might have high latency. Increase Scrapy's
DOWNLOAD_TIMEOUTsetting and implement a retry middleware. Also, consider switching networks; for example, residential vs datacenter rotating proxies have different speed characteristics. - TLS/SSL Errors: These can sometimes occur with HTTPS sites through a proxy. Use port 7070 for HTTPS connections. You can try adjusting Scrapy's
DOWNLOADER_CLIENT_TLS_METHODto'TLS'or settingREQUEST_FINGERPRINTER_IMPLEMENTATIONto'2.7'in newer Scrapy versions. Check the current Scrapy docs for TLS configuration.
Tips for Running Scrapy at Scale with Proxies
When scraping large volumes, efficient proxy use is key to performance and cost management.
- Respect Concurrency Limits: Your account supports up to 1,000 concurrent connections. Tune Scrapy's
CONCURRENT_REQUESTS,CONCURRENT_REQUESTS_PER_DOMAIN, andDOWNLOAD_DELAYto stay within this limit and be polite to target sites. Read our guide on planning concurrency for crawlers. - Use Sticky Sessions Wisely: For logged-in scraping or sites that track sessions, use a
sidper domain or user. This reduces the chance of CAPTCHA triggers. However, for broad crawling, per-request rotation (omitting thesid) is often better. Understand the trade-offs in sticky vs rotating sessions. - Monitor Traffic and Balance Keep an eye on your dashboard to see GB usage per network. Use the volume rate discounts, the price per GB drops automatically as your monthly usage increases on a network. Learn more at how monthly volume rates are applied.
- Implement Retry Logic: Use Scrapy's built-in
RETRY_TIMESandRETRY_HTTP_CODESsettings, or write a custom retry middleware that can also rotate the proxy on certain failures. This improves reliability for website uptime and change monitoring. - Cache and Compress: To save bandwidth and reduce costs, enable
HTTPCACHE_ENABLEDin Scrapy for idempotent requests and ensure your spider handlesAccept-Encodingheaders. Our guide on save bandwidth with compression and caching has details.
Using the Meta Proxy Middleware for Advanced Control
For complex projects, writing a custom downloader middleware gives you the most control. This middleware can select different proxy users based on the spider name, target domain, or request priority. Below is a simplified middleware that chooses a network based on a spider attribute.
# In your middlewares.py
from scrapy import signals
class RotatingProxyMiddleware:
def process_request(self, request, spider):
if 'proxy' in request.meta:
return # Already set
# Assume spider has an attribute like proxy_network
network = getattr(spider, 'proxy_network', 'res')
proxy_user = f'LOGIN_net.{network}_cc.us'
request.meta['proxy'] = f'http://{proxy_user}:PASSWORD@gw.rotatingproxy.cc:7070'
# In settings.py
DOWNLOADER_MIDDLEWARES = {
'myproject.middlewares.RotatingProxyMiddleware': 543,
}
This pattern is useful when you run different spiders for different purposes, like one using Google search proxies and another using Instagram proxies.
Testing Your Proxy Connection
Before launching a full crawl, run a quick test from the command line or a script to verify authentication and network access. You can use curl as shown in our curl proxy guide. In Scrapy, you can add a simple test spider that fetches an IP check page and logs the result. This helps catch configuration errors early.
Managing Costs with Pay-As-You-Go
Since you are billed per GB for traffic that passes through the gateway, optimize your spider to avoid unnecessary downloads. Use robots.txt compliance (see how to read robots.txt), limit the domains you crawl, and prefer API endpoints over HTML when available. Set monthly GB caps on your proxy users in the dashboard as a safety measure.
Questions
Can I use different proxy networks (residential, mobile) within the same Scrapy spider?
Yes. You can change the network per request by modifying the <code>net.</code> option in the proxy username. For example, use <code>net.mob</code> for one request and <code>net.dc</code> for another. This lets you tailor the IP type to the target site's blocking behavior.
How do I make Scrapy rotate to a new IP on every single request?
Omit the <code>sid</code> (session ID) option from your proxy username. Each new connection will then receive a fresh IP from the selected network and location. This happens by default when you don't set a session.
My spider is getting 403 errors from the target site even though the proxy works. What should I do?
A 403 from the target site indicates your request was blocked, not a proxy error. This could be due to the IP reputation, request headers, or rate. Try switching networks (e.g., from datacenter to residential), adding realistic headers, and increasing delays between requests. See target site returns 403 for more.
Does Scrapy resolve DNS through the proxy when using RotatingProxy?
Yes. When you configure Scrapy to use our gateway via the <code>proxy</code> meta setting, DNS queries for the target hostname are performed by the proxy exit node. This prevents DNS leaks and ensures the target site sees the proxy IP for both connection and resolution.
How can I check how much proxy traffic my Scrapy spider has used?
Log into your RotatingProxy dashboard. The overview page shows your current balance and data usage per network for the current month. You can also view detailed daily usage graphs and download reports. For API monitoring, use the API endpoint for usage.
What is the best way to handle CAPTCHAs when using rotating proxies with Scrapy?
Rotating proxies help reduce CAPTCHAs by distributing requests across many IPs, but they don't solve them. The best approach is to avoid triggering CAPTCHAs: use polite crawling speeds, realistic sessions, and mimic human behavior. If you encounter a CAPTCHA, your spider should detect it and pause or switch tasks. We do not offer CAPTCHA solving services.
Start with one top-up, use any network
Create an account in a minute, add $40 or more, and the same balance pays for residential, mobile, datacenter and ISP traffic.