> For the complete documentation index, see [llms.txt](https://developers.oxylabs.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developers.oxylabs.io/integrations/cn/proxy-integrations/scrapy.md).

# Scrapy

将 Scrapy 与 Oxylabs 代理集成，以使用简单的分步指南构建快速的异步网页爬虫。

[Scrapy](https://scrapy.org/) 是一个开源 Python 框架，专为大规模网页抓取和数据提取而设计。默认情况下，Scrapy 会直接从你的本地网络路由请求。

按照以下步骤集成下面的 Oxylabs 代理：

* [**住宅代理和移动代理**](#residential-and-mobile-proxies)
* [**数据中心代理**](#datacenter-proxies)
* [**独享数据中心代理（企业版）**](#dedicated-datacenter-proxies-enterprise)
* [**独享数据中心代理（自助服务版）**](#dedicated-datacenter-proxies-self-service)
* [**ISP代理**](#isp-proxies)
* [**独享ISP代理**](#dedicated-isp-proxies)

{% stepper %}
{% step %}

### 选择集成方式

Scrapy 支持通过代理路由请求的两种主要方法： [**请求 Meta 参数**](#method-1-request-meta-parameter) （按请求配置）和 [**自定义下载中间件**](#method-2-custom-downloader-middleware-recommended) （全项目配置）。

#### 方法 1：请求 Meta 参数

将代理认证详情直接传入单个 `scrapy.Request` 实例，通过 `meta` 字典。此方法适合简单爬虫，或当不同请求需要特定代理配置时使用。

```python
import scrapy

class OxylabsSpider(scrapy.Spider):
    name = "oxylabs_spider"
    
    def start_requests(self):
        url = "https://ip.oxylabs.io/"
        proxy = "http://username:password@host:port"
        
        yield scrapy.Request(
            url=url,
            callback=self.parse,
            meta={"proxy": proxy}
        )

    def parse(self, response):
        ip_address = response.css("pre::text").get()
        self.logger.info(f"通过 Oxylabs 代理已连接。当前 IP: {ip_address}")
```

#### 方法 2：自定义下载中间件（推荐）

若要在不修改爬虫代码的情况下自动将代理应用到所有请求，请实现一个自定义 Scrapy 下载中间件。

打开 Scrapy 项目的 `middlewares.py` 文件，并添加 `OxylabsProxyMiddleware` 类：

```python
class OxylabsProxyMiddleware:
    @classmethod
    def from_crawler(cls, crawler):
        return cls(crawler.settings)

    def __init__(self, settings):
        self.username = settings.get("OXYLABS_USERNAME")
        self.password = settings.get("OXYLABS_PASSWORD")
        self.endpoint = settings.get("OXYLABS_ENDPOINT")

    def process_request(self, request, spider):
        host = f"http://{self.username}:{self.password}@{self.endpoint}"
        request.meta["proxy"] = host
```

然后，注册该中间件，并在 `settings.py`:

```python
# Oxylabs Credentials
OXYLABS_USERNAME = "username"
OXYLABS_PASSWORD = "password"
OXYLABS_ENDPOINT = "host:port"

# Enable Downloader Middleware
DOWNLOADER_MIDDLEWARES = {
    "myproject.middlewares.OxylabsProxyMiddleware": 100,
    "scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware": 110,
}
```

{% endstep %}

{% step %}

### 配置你的代理

调整代理详情和 Oxylabs 代理用户凭据（在 [Oxylabs 控制面板](https://dashboard.oxylabs.io/en/)中创建）以匹配你选择的代理类型：

* [住宅代理和移动代理](#residential-and-mobile-proxies)
* [数据中心代理](#datacenter-proxies)
* [独享数据中心代理（企业版）](#dedicated-datacenter-proxies-enterprise)
* [独享数据中心代理（自助服务版）](#dedicated-datacenter-proxies-self-service)
* [ISP代理](#isp-proxies)
* [独享ISP代理](#dedicated-isp-proxies)

#### 住宅代理和移动代理

**主机：** `pr.oxylabs.io`

**端口：** `7777`

**用户名：** `customer-username`

**密码：** `password`

{% hint style="warning" %}
**注意：** 别忘了添加 `customer-` 用户名前缀。
{% endhint %}

你还可以使用 **附加参数** 搭配住宅代理和移动代理来设置地理位置（国家/地区、州、省、市等）并控制会话。查看 [住宅代理文档](/products/cn/proxies/residential-proxies.md) 了解更多。下表概述了可用参数及其示例值。

<table><thead><tr><th width="167">代理参数</th><th width="498">示例</th></tr></thead><tbody><tr><td><a href="/products/cn/proxies/residential-proxies/location-settings/select-country.md#country-specific-entry-nodes">国家入口节点</a></td><td><p><strong>主机：</strong> <code>us-pr.oxylabs.io</code></p><p><strong>端口：</strong> <code>10000</code></p></td></tr><tr><td><a href="/products/cn/proxies/residential-proxies/location-settings/select-country.md">国家/地区</a></td><td><strong>用户：</strong> <code>customer-username-cc-US</code></td></tr><tr><td><a href="/products/cn/proxies/residential-proxies/location-settings/select-state.md">州</a></td><td><strong>用户：</strong> <code>customer-username-st-US_texas</code></td></tr><tr><td><a href="/products/cn/proxies/residential-proxies/location-settings/select-city.md">城市</a></td><td><strong>用户：</strong> <code>customer-username-city-paris</code></td></tr><tr><td><a href="/products/cn/proxies/residential-proxies/location-settings/continent.md">洲</a></td><td><strong>用户：</strong> <code>customer-username-cn-NA</code></td></tr><tr><td><a href="/products/cn/proxies/residential-proxies/location-settings/zip-postal-code.md">ZIP/邮政编码</a></td><td><strong>用户：</strong> <code>customer-username-cc-US-postalcode-90210</code></td></tr><tr><td><a href="/products/cn/proxies/residential-proxies/location-settings/asn-targeting.md">ASN 定向</a></td><td><strong>用户：</strong> <code>customer-username-ASN-21928</code></td></tr><tr><td><a href="/products/cn/proxies/residential-proxies/session-control.md">会话</a> （最长 1440 分钟）</td><td><strong>用户：</strong> <code>customer-username-sessid-qwerty123-sesstime-1440</code></td></tr><tr><td><a href="broken://spaces/ZwEHB9k4MH4pDy80n9mF/pages/a7b2e5c423ead1821bf87e8d883aceae933c6fae">黏性会话</a></td><td><p><strong>主机：</strong> <code>us-pr.oxylabs.io</code></p><p><strong>端口：</strong> <code>10001</code></p></td></tr></tbody></table>

#### 数据中心代理

**主机：** `dc.oxylabs.io`

**端口：** `8001`

**用户名：** `user-userername`

**密码：** `password`

{% hint style="warning" %}
**注意：** 别忘了添加 `user-` 用户名前缀。
{% endhint %}

{% tabs %}
{% tab title="按 IP 计费订阅" %}
端口是从 [代理列表](/products/cn/proxies/datacenter-proxies/proxy-list.md)的 IP 地址的顺序编号。因此，端口 `8001` 将始终使用你列表中的第一个 IP 地址。你也可以通过将端口设置为 [代理 IP 轮换](/products/cn/proxies/datacenter-proxies/ip-control.md) 来启用 `8000`.

此外，你可以指定 [地理位置](/products/cn/proxies/datacenter-proxies/select-country.md)，例如美国，方法是将 **代理用户名** 设置为 `user-USERNAME-country-US`.
{% endtab %}

{% tab title="按流量计费订阅" %}
该端口 `8001` 会随机选择一个 IP 地址，但在会话期间保持一致。或者，你可以通过使用端口 [轮换代理 IP](/products/cn/proxies/datacenter-proxies/ip-control.md) 来在每个请求中更换 IP `8000`.

如果你想使用特定的 [地理位置](/products/cn/proxies/datacenter-proxies/select-country.md)，例如美国，请将代理用户名设置为 `user-USERNAME-country-US`.
{% endtab %}
{% endtabs %}

#### 独享数据中心代理（企业版）

**主机：** `1.2.3.4` （来自你的 [代理列表](/products/cn/proxies/dedicated-datacenter-proxies/enterprise/proxy-lists.md))

**端口：** `60000` （HTTP）或 `1180` (SOCKS5)

**用户名：** `username`

**密码：** `password`

对于企业版独享数据中心代理（通过销售团队购买），你需要从已获取的 [代理列表](/products/cn/proxies/dedicated-datacenter-proxies/enterprise/proxy-lists.md).

#### 独享数据中心代理（自助服务版）

**主机：** `ddc.oxylabs.io`

**端口：** `8001`

**用户名：** `user-userername`

**密码：** `password`

{% hint style="warning" %}
**注意：** 别忘了添加 `user-` 用户名前缀。
{% endhint %}

对于自助式独享数据中心代理（通过 Oxylabs 仪表盘购买），端口表示从已获取的 [代理列表](/products/cn/proxies/dedicated-datacenter-proxies/self-service/proxy-list.md)的 IP 地址的顺序编号。如果你希望每个请求都获得不同的 IP，请将端口改为 `8000` 以启用 [代理轮换](/products/cn/proxies/dedicated-datacenter-proxies/self-service/proxy-rotation.md).

#### ISP代理

**主机：** `isp.oxylabs.io`

**端口：** `8001`

**用户名：** `user-username`

**密码：** `password`

{% hint style="warning" %}
**注意：** 别忘了添加 `user-` 用户名前缀。
{% endhint %}

对于 ISP 代理，端口会分配给一个特定的 IP 地址及其位置。因此，端口 `8001` 将始终选择你 [代理列表](/products/cn/proxies/isp-proxies/proxy-list.md).

中的第一个 IP。如果你希望每个请求都获得不同的 IP，请将端口改为 `8000` 以启用 [代理轮换](/products/cn/proxies/isp-proxies/proxy-rotation.md).

#### 独享ISP代理

**主机：** `disp.oxylabs.io`

**端口：** `8001`

**用户名：** `user-USERNAME`

**密码：** `PASSWORD`

{% hint style="warning" %}
**注意：** 别忘了添加 `user-` 用户名前缀。
{% endhint %}

您需要选择分配给所购买的 IP 地址的端口 [代理列表](/products/cn/proxies/dedicated-isp-proxies/self-service/proxy-list.md)，你可以在 Oxylabs 仪表盘上找到。 `8001` 端口会为所有请求从你的列表中选择第一个 IP 地址。使用端口 `8000` 可自动进行 [代理 IP 轮换](/products/cn/proxies/dedicated-isp-proxies/self-service/proxy-rotation.md).
{% endstep %}

{% step %}

### 执行爬虫

使用 `crawl` 命令运行你的 Scrapy 爬虫：

```bash
scrapy crawl oxylabs_spider
```

如果配置正确，Scrapy 将通过 Oxylabs 代理网关执行请求，并记录分配的外部出口 IP 地址。
{% endstep %}
{% endstepper %}


---

# 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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://developers.oxylabs.io/integrations/cn/proxy-integrations/scrapy.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
