
Scrapy can use Magnetic Proxy through its standard HTTP proxy support. Set a complete proxy URL on each request through Scrapy's proxy metadata, then choose rotating or sticky behavior in the Magnetic Proxy connection profile. No Magnetic Proxy-specific Scrapy SDK is required.
The implementation has three separate responsibilities: Scrapy controls scheduling and retries, the proxy profile controls route and session behavior, and the spider validates whether the response contains usable data.
Scrapy's HttpProxyMiddleware documentation supports a per-request proxy value. For Scrapy 2.18 with the default HTTP/1.1 download handler, use Magnetic Proxy's HTTP endpoint for both HTTP and HTTPS destination URLs, for example http://customer-USERNAME:PASSWORD@rs.magneticproxy.net:1080. Replace the placeholders with the credentials from the active profile and keep the value outside source control. Do not switch that value to an HTTPS or SOCKS proxy URL unless the project's active download handler explicitly supports that proxy scheme.
The proxy mode should follow the unit of work, while retry behavior should follow the failure type. On smaller screens, swipe horizontally to view all columns.
| Scrapy workload | Proxy mode | Configuration rule | Operational check |
|---|---|---|---|
| Independent product or listing pages | Rotating | Use the profile without sessid. |
Validate item fields; an HTTP 200 alone is not a usable result. |
| Pagination or cookie-dependent sequence | Sticky | Reuse one alphanumeric sessid for the sequence. Add sesstime only when the sequence needs an explicit duration instead of the documented default. |
Restart or flag the sequence if route continuity is essential and the observed route changes. |
| Regional QA | Sticky per market | Create one profile for each requested country, region, or city and one session per market run. | Verify the observed location. A sticky session may fall back if its proxy is unavailable; use the documented hardcountry option only when a strict-country failure is preferable to fallback. |
| 429, timeout, or selected 5xx response | Bounded retry | Let Scrapy retry only documented transient failures, with a small cap and backoff. | Track retry reason and give-up count. A new route is not proof that the request should succeed. |
The smallest implementation sets the complete proxy URL in request metadata. Keep that value in an environment variable so the connection profile can change without editing spider code.
Export MP_PROXY_URL in the process environment before starting Scrapy. A .env file is not loaded by Scrapy automatically unless the project adds its own environment loader.
import os
import scrapy
class CatalogSpider(scrapy.Spider):
name = "catalog"
allowed_domains = ["example.com"]
async def start(self):
proxy_url = os.getenv("MP_PROXY_URL")
if not proxy_url:
raise RuntimeError(
"Set MP_PROXY_URL before starting Scrapy."
)
yield scrapy.Request(
"https://example.com/catalog",
meta={"proxy": proxy_url},
callback=self.parse,
)
def parse(self, response):
# Validate the fields your workflow requires.
yield {"title": response.css("h1::text").get()}
For a project-wide setting, use the downloader middleware below instead of repeating meta={"proxy": ...} on every request. Keep per-request proxy metadata only when a request intentionally overrides the project-wide profile.
# myproject/middlewares.py
import os
class MagneticProxyMiddleware:
def __init__(self):
try:
self.proxy_url = os.environ["MP_PROXY_URL"]
except KeyError as exc:
raise RuntimeError(
"Set MP_PROXY_URL before starting Scrapy."
) from exc
def process_request(self, request):
request.meta.setdefault("proxy", self.proxy_url)
Replace myproject with the Python package name created by scrapy startproject. The middleware order 350 runs this assignment before Scrapy's built-in HttpProxyMiddleware, which parses the URL and applies proxy authentication.
Scrapy already includes retry controls. Its current documentation lists two retries by default, in addition to the initial request, and a default set of transient HTTP status codes. Keep the initial policy simple and change it only with target-specific evidence.
# settings.py (Scrapy 2.18+)
DOWNLOADER_MIDDLEWARES = {
"myproject.middlewares.MagneticProxyMiddleware": 350,
}
RETRY_ENABLED = True
RETRY_TIMES = 2
DOWNLOAD_TIMEOUT = 30
AUTOTHROTTLE_ENABLED = True
AUTOTHROTTLE_START_DELAY = 1.0
AUTOTHROTTLE_MAX_DELAY = 30.0
AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
CONCURRENT_REQUESTS_PER_DOMAIN = 2
ROBOTSTXT_OBEY = True
Scrapy's RetryMiddleware documentation is the source of truth for retry defaults. Its AutoThrottle documentation explains how latency and concurrency interact. Respect target rules even when a higher request rate is technically possible.
Keep two connection profiles outside the code:
sessid so independent requests can use rotating routes.sessid. Add sesstime only when the stateful sequence needs an explicit duration instead of the documented default.The Scrapy implementation remains the same. The environment variable points to the profile appropriate for that spider or job. If different requests inside one spider need different modes, assign the appropriate profile URL per request rather than mutating one shared string.
Use this approach when Scrapy is already the crawler and you need a standard residential proxy layer with configurable rotation, sticky sessions, and location parameters. If the workflow requires browser execution, JavaScript rendering, or a third-party download handler, validate that component's proxy support separately; this guide does not imply a native integration or guaranteed compatibility with every handler.
Review Magnetic Proxy's Web Scraping Capsule and connection documentation, then test the exact profile against a small authorized Scrapy job before scaling.
Check the most Frequently Asked Questions
What is a rotating proxy?
A rotating proxy routes requests through IPs selected from a pool according to the connection configuration. It can distribute independent requests across different network routes, but it does not grant access rights, prevent rate limits or bans, or override a target's rules.
How does proxy rotation work?
Proxy rotation works through a backconnect gateway: your application connects to one endpoint, and the gateway selects a different IP from its pool for each request. The application never manages individual IPs — the gateway handles selection, health-checking, and rotation automatically based on your configuration and the target's response.
When should I use sticky sessions instead of rotating proxies?
Use sticky sessions when your workflow requires the same IP across multiple requests — login flows, paginated navigation, or any sequence where the target tracks session state. Per-request rotation breaks authenticated workflows because the server assigns session cookies to a specific IP, and rotating that IP ends the session immediately.
Are rotating proxies legal?
Rotating proxies are network-routing tools. Whether a particular use is permitted depends on the data, access method, target terms, privacy obligations, applicable laws, and jurisdiction. Use them only for authorized, lawful workflows; consult qualified counsel for your specific case.
Here’s how Profile Peeker enables organizations to transform profile data into business opportunities.