> For the complete documentation index, see [llms.txt](https://docs.ipdunar.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.ipdunar.com/integrations/scraping-tools/scrapy.md).

# Scrapy

Scrapy plugs into ipdunar through its built-in `HTTP_PROXY` envvar support and the `HttpProxyMiddleware`. For per-request rotation, add `scrapy-rotating-proxies`.

## Single static proxy

In `settings.py`:

```python
HTTPPROXY_AUTH_ENCODING = "latin-1"

DOWNLOADER_MIDDLEWARES = {
    "scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware": 750,
}
```

Then in each request:

```python
def start_requests(self):
    proxy = "http://ipdunar_s1a2b3c4d5e-type-res-region-us:PASSWORD@gate.ipdunar.com:7777"
    for url in self.start_urls:
        yield scrapy.Request(url, meta={"proxy": proxy})
```

Or set the env vars before launching:

```bash
export HTTP_PROXY="http://ipdunar_s1a2b3c4d5e-type-res-region-us:PASSWORD@gate.ipdunar.com:7777"
export HTTPS_PROXY="$HTTP_PROXY"
scrapy crawl myspider
```

## ISP rotation with `scrapy-rotating-proxies`

```bash
pip install scrapy-rotating-proxies
```

`settings.py`:

```python
ROTATING_PROXY_LIST_PATH = "/path/to/isp.txt"      # one ip:port:user:pass per line
# or:
ROTATING_PROXY_LIST = [
    "http://ipdunar_s1a2b3c4d5e:PASSWORD@198.51.100.42:8000",
    "http://ipdunar_s1a2b3c4d5e:PASSWORD@198.51.100.43:8000",
]

DOWNLOADER_MIDDLEWARES = {
    "rotating_proxies.middlewares.RotatingProxyMiddleware": 610,
    "rotating_proxies.middlewares.BanDetectionMiddleware": 620,
}

# Optional tuning
ROTATING_PROXY_BAN_POLICY = "rotating_proxies.policy.BanDetectionPolicy"
ROTATING_PROXY_BACKOFF_BASE = 300                  # seconds
```

The middleware tracks failures per proxy and skips banned ones. Combine with `RETRY_HTTP_CODES = [429, 502, 522, 524]` for transient gateway errors.

## Residential dynamic session rotation

You don't need an external list — generate sessions on the fly:

```python
import random, string

def session_proxy(country="us"):
    sid = "".join(random.choices(string.ascii_lowercase + string.digits, k=8))
    user = f"ipdunar_s1a2b3c4d5e-type-res-region-{country}-session-{sid}-sesstime-10"
    return f"http://{user}:PASSWORD@gate.ipdunar.com:7777"

class MySpider(scrapy.Spider):
    def start_requests(self):
        for url in self.start_urls:
            yield scrapy.Request(url, meta={"proxy": session_proxy()})
```

## Adding the ipdunar tag

```python
yield scrapy.Request(
    url,
    meta={"proxy": proxy},
    headers={"X-IPdunar-Tag": "campaign-acme-q2"},
)
```

The tag shows up in your traffic analytics — see [Statistics](https://docs.ipdunar.com/products/overview/statistics.md).

## Verify

```python
def parse(self, response):
    self.logger.info("Exit IP: %s", response.headers.get(b"X-IPdunar-Exit-IP", b"").decode())
```

## Common pitfalls

* **`HttpProxyMiddleware` disabled** — Scrapy enables it by default, but custom `DOWNLOADER_MIDDLEWARES` dicts must keep it.
* **CONCURRENT\_REQUESTS too high for a small ISP batch** — your batch caps at N IPs; concurrency above N just queues. Match `CONCURRENT_REQUESTS_PER_DOMAIN` to your pool size.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.ipdunar.com/integrations/scraping-tools/scrapy.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
