> 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/documentation/cn/kai-shi-shi-yong/kuai-su-kai-shi-web-api.md).

# 快速开始：Web API

只需五分钟，即可从 API 密钥开始完成您的首次 Oxylabs Web API 搜索和抓取。

{% hint style="success" %}
已经熟悉基础知识？请查看 [Web API 文档](https://developers.oxylabs.io/products/cn/web-api.md).
{% endhint %}

[**Oxylabs Web API**](https://oxylabs.io/products/web-api) 为您的应用程序或 AI 代理提供两项在开放网络上出奇难以实现的功能： **找到合适的最新页面，并可靠地提取其中的数据**。一个端点可搜索实时网络，另一个端点可抓取任意页面（渲染 JavaScript 并处理访问挑战），并返回可直接使用的干净数据。

<table><thead><tr><th width="159">端点</th><th>提供内容</th><th>适用场景</th></tr></thead><tbody><tr><td><a href="https://developers.oxylabs.io/products/web-api/search"><code>POST /v1/search</code></a></td><td>排序后的结果：标题、描述、URL</td><td>您不知道哪个页面包含所需答案</td></tr><tr><td><a href="https://developers.oxylabs.io/products/web-api/scrape"><code>POST /v1/scrape</code></a></td><td>以 Markdown、HTML、JSON 或屏幕截图形式返回单个页面</td><td>您知道 URL，并需要获取页面内容</td></tr></tbody></table>

这两个端点专为配合使用而设计： **通过搜索查找，再通过抓取提取。** 本快速入门指南涵盖：

* **手动集成** ——编写自己的代码直接调用 API。
* **轻松集成 AI** ——通过专有 AI 代理或自定义 AI 代理使用 Web API。

{% hint style="success" %}
想在完整实施前，先通过简单的图形界面环境测试 Web API？请查看 [Web API Playground](https://developers.oxylabs.io/products/web-api/playground).
{% endhint %}

## 设置和 API 密钥 <a href="#docs-internal-guid-4566d081-7fff-6c77-5105-4c81aa345516" id="docs-internal-guid-4566d081-7fff-6c77-5105-4c81aa345516"></a>

1. **创建账户：** 在 [Oxylabs 控制面板](https://dashboard.oxylabs.io/).
2. **中注册** 点击 **+ 添加产品实例** ，然后在 Web access（网页访问）类别中选择 Web API。
3. **进行设置：** 选择实例名称、产品使用限制（可选），然后创建实例。
4. **获取凭据：** 在控制面板首页的实例表格中点击 Web API 实例，即可获取 API 密钥。
5. **将您的 API 密钥导出** 到项目环境中（例如操作系统终端，或项目工作区中的 CLI 终端）：

```bash
export OXYLABS_WEB_API_KEY=your_api_key_here
```

{% hint style="info" %}
**注意：** 始终将密钥保存在服务器端。切勿将其提交到源代码管理系统，或暴露在客户端代码中。
{% endhint %}

## Web API 集成

#### 要将其接入 AI 代理？

跳转到 [AI 代理集成](#ai-agent-integration) 即可通过一条命令开始使用。

#### 要构建自己的自定义集成？

从下方的手动集成开始。

### 手动集成

根据您的数据需求，您可以单独使用 Web API 端点进行网页搜索或抓取，也可以将其用作完整的数据采集与交付流程。

{% stepper %}
{% step %}

#### 搜索页面（`/search`)

查找哪些页面包含您定义的 `query`:

```bash
curl https://webapi.oxylabs.io/v1/search \
  -H "Authorization: Bearer $OXYLABS_WEB_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"query": "eu ai act compliance deadlines", "max_results": 3}'
```

<details>

<summary>输出示例</summary>

```json
{
  "state": "done",
  "results": [
    {
      "title": "Implementation Timeline | EU Artificial Intelligence Act",
      "outline": [
        "Date 2 August 2025 Providers: need to be compliant with the AI Act by 2 August 2027..."
      ],
      "url": "https://artificialintelligenceact.eu/implementation-timeline/",
      "metadata": { "position": 1 }
    }
  ],
  "params": { "query": "eu ai act compliance deadlines", "location": null, "max_results": 3 },
  "metadata": { "timestamp": 1787431568, "request_id": "1788875675880097469" }
}
```

</details>
{% endstep %}

{% step %}

#### 抓取页面（`/scrape`)

传入目标 `url` 和所需的输出格式（`markdown`, `html`, `json`, `screenshot`），即可抓取任意公开网站的完整页面内容。以下是请求 Markdown 格式页面内容的示例：

```bash
curl https://webapi.oxylabs.io/v1/scrape \
  -H "Authorization: Bearer $OXYLABS_WEB_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"url": "https://artificialintelligenceact.eu/implementation-timeline/",
       "output": ["markdown"]}'
```

{% endstep %}

{% step %}

#### 完整流程（从搜索到抓取）

`outline` 在 `/search` 中找到的内容是截断片段列表，通常不适用于高级用例或 AI 工作流。

要通过单次查询获取结构化数据，请使用 `/search` 根据您的 `query` 搜索相关数据，并将结果 URL 传递给 `/scrape` 以检索数据。以下是一个可完整运行的 Python 示例：

{% code expandable="true" %}

```python
import os, requests

API = "https://webapi.oxylabs.io"
HEADERS = {"Authorization": f"Bearer {os.environ['OXYLABS_WEB_API_KEY']}"}

def research(question: str, read_top: int = 2) -> list[dict]:
    # 1. 查找目标 URL
    hits = requests.post(
        f"{API}/v1/search",
        headers=HEADERS,
        json={"query": question, "max_results": 10},
    )
    hits.raise_for_status()
    # 2. 提取完整页面内容为 Markdown
    pages = []
    for hit in hits.json()["results"][:read_top]:
        page = requests.post(
            f"{API}/v1/scrape",
            headers=HEADERS,
            json={"url": hit["url"], "output": ["markdown"]},
            timeout=120,
        )
        if not page.ok:
            print(f"skipped {hit['url']}: {page.status_code}")
            continue
        pages.append(
            {
                "url": hit["url"],
                "title": hit["title"],
                "content": page.json()["results"][0]["markdown"],
            }
        )
    return pages

for page in research("eu ai act compliance deadlines"):
    print(f"--- {page['title']} ({page['url']})")
    print(page["content"][:500])
```

{% endcode %}
{% endstep %}
{% endstepper %}

{% hint style="info" %}
**以上所有内容都是 Realtime——结果会在响应中返回。** 对于大批量数据采集，我们建议将爬虫作为作业运行，通过 `/v1/async/scrape` 并通过轮询、回调或直接发送到你的存储桶来交付结果。请参阅 [交付模式](https://developers.oxylabs.io/products/web-api/scrape/delivery-modes).
{% endhint %}

### AI 智能体集成

Oxylabs Web API 专为便于 AI 智能体工作流而设计，可使用 **Agent Skills**, **MCP** （模型上下文协议）或简单的 **单提示词集成**。获取 API 密钥后，选择集成方式。

{% tabs %}
{% tab title="单提示词集成" icon="rectangle-terminal" %}
**单页集成提示词——将提示词粘贴到编程智能体中，让它为你构建自定义集成。**

如果你希望 AI 编程助手（例如 Claude Code、Cursor 或 Copilot）为你构建集成，请粘贴以下提示词：

{% code overflow="wrap" expandable="true" %}

```
将 Oxylabs Web API 集成到此项目中，用于实时网页搜索和页面读取。

阅读 https://developers.oxylabs.io/products/web-api/for-agents.md 并遵循
其中的说明。该页面包含基础 URL、身份验证、两个端点的架构、参考代码、错误与重试
规则，以及需要满足的检查清单。如果页面无法加载，请停止并告诉我；不要
凭记忆重新构建 API。

写入任何内容前，先确定实施路径并告诉我：
- 如果此项目自身的代码会在运行时调用 API？-> 按页面
  指定的方式编写客户端，并遵循此代码库现有的出站 HTTP 调用方式。
- 如果网页访问是供你在本次会话中使用，而不是供项目代码使用？
  -> 按照页面说明安装 MCP 服务器和技能。

密钥位于 OXYLABS_WEB_API_KEY 或此处的 .env 文件中。如果两处都没有，请询问我。绝不要
打印密钥：不要将其写入代码、日志、测试，也不要在回复中告诉我。

编写测试前先验证它能正常工作：执行一次真实搜索，抓取一个搜索
结果中的 URL，并向我展示两个请求 ID。如果调用返回 401，请停止并告诉我。

如果抓取结果为空或仅包含少量内容，请使用 run_js: true 重试一次。如果结果仍然
为空，且网站使用国家或地区顶级域名（.lt、.es、.co.uk），请再次使用 run_js 重试，并将
location 设置为对应的国家或地区，然后报告该页面无法读取。

然后针对模拟传输层添加重试和错误映射测试，并运行测试。
如果无法在此环境中运行命令，请说明一次，并提供我需要运行的
确切命令。

请汇报：你采用的方案、页面上每个检查项是否完成、
我仍需自行完成的工作，以及你未能完成的事项。不要问我
是否继续；直接完成工作。
```

{% endcode %}

如需查看完整示例并进一步了解 Web API 集成，请参阅 [文档](https://developers.oxylabs.io/products/web-api).
{% endtab %}

{% tab title="智能体技能" icon="head-side-gear" %}
**智能体技能——安装有关如何使用 API 的知识，无需运行服务器。**

使用以下终端命令添加官方智能体技能，让你的 AI 智能体了解如何通过 Oxylabs Web API 进行搜索、抓取、引用来源和开展网络研究：

```bash
npx skills add oxylabs/web-api-skills
```

现在，你的智能体已掌握 Oxylabs Web API 及其使用方法的全部知识。如需进一步了解 Web API 智能体技能，请参阅我们的 [文档](https://developers.oxylabs.io/ai-workflows/agent-skills).
{% endtab %}

{% tab title="MCP 服务器" icon="server" %}
**MCP 服务器——为所有 MCP 客户端提供带类型定义的搜索、抓取工具和专用抓取工具。**

连接到我们的官方 MCP 服务器或自行托管该服务器，即可将 Web API 搜索、抓取和提取工具直接提供给 Claude Code、Cursor 或你的自定义 AI 智能体。

最简单的实现方式是将智能体指向 Oxylabs 托管的服务器，从而将该服务器添加到客户端： `https://mcp.oxylabs.io/web-api-mcp`:

<details>

<summary><i class="fa-claude">:claude:</i>  <strong>Claude Code</strong></summary>

```bash
claude mcp add --transport http --scope user oxylabs-web-api \
  https://mcp.oxylabs.io/web-api-mcp \
  --header "Authorization: Bearer ${OXYLABS_WEB_API_KEY}"
```

</details>

<details>

<summary><i class="fa-openai">:openai:</i>  <strong>ChatGPT/Codex</strong></summary>

```bash
codex mcp add oxylabs-web-api \
  --url https://mcp.oxylabs.io/web-api-mcp \
  --bearer-token-env-var OXYLABS_WEB_API_KEY
```

</details>

<details>

<summary><i class="fa-cursor">:cursor:</i>  <strong>Cursor</strong> （或其他支持自定义标头的客户端）</summary>

对于支持使用自定义标头连接远程 MCP 服务器的客户端，请在其 MCP 配置中添加服务器 URL 和 `Authorization` 标头。例如，在 Cursor 的 `mcp.json`:

```json
{
  "mcpServers": {
    "oxylabs-web-api": {
      "url": "https://mcp.oxylabs.io/web-api-mcp",
      "headers": {
        "Authorization": "Bearer ${env:OXYLABS_WEB_API_KEY}"
      }
    }
  }
}
```

字段名称可能因客户端而异，请查阅客户端文档，了解如何添加带标头的远程 MCP 服务器。

</details>

如需进一步了解 Web API MCP 集成或如何自行托管 Oxylabs 官方服务器，请参阅 [MCP 服务器](https://developers.oxylabs.io/ai-workflows/mcp).
{% endtab %}
{% endtabs %}

### 必要参数

#### /search <a href="#docs-internal-guid-5786cd1b-7fff-0a37-d2dd-abcf76c7e3ef" id="docs-internal-guid-5786cd1b-7fff-0a37-d2dd-abcf76c7e3ef"></a>

<table><thead><tr><th width="121">参数</th><th width="86">类型</th><th>描述</th></tr></thead><tbody><tr><td><code>query</code></td><td>字符串</td><td>搜索关键词或短语</td></tr><tr><td><code>max_results</code></td><td>整数</td><td>要返回的自然搜索结果数量（<code>1-20</code>)</td></tr><tr><td><code>location</code></td><td>字符串</td><td>两位国家代码（例如， <code>"DE"</code>, <code>"US"</code>），用于本地化搜索</td></tr></tbody></table>

#### /scrape

<table><thead><tr><th width="111">参数</th><th width="99">类型</th><th>描述</th></tr></thead><tbody><tr><td><code>url</code></td><td>字符串</td><td>要抓取的网址</td></tr><tr><td><code>output</code></td><td>数组</td><td>返回格式： <code>"html"</code> （默认）、 <code>"markdown"</code>, <code>"json"</code>, <code>"screenshot"</code></td></tr><tr><td><code>json</code></td><td>对象</td><td>用于通过提示词或架构进行自定义 AI 解析</td></tr><tr><td><code>location</code></td><td>字符串</td><td>两位国家代码（例如， <code>"DE"</code>, <code>"US"</code>）。某些专用抓取器使用不同的格式。请参阅 <a href="https://developers.oxylabs.io/products/cn/web-api/scrape/zhuan-yong-zhua-qu-qi.md">专用抓取器</a>.</td></tr><tr><td><code>run_js</code></td><td>布尔值</td><td>在提取内容前，使用真实浏览器渲染页面。速度较慢，客户端超时时间应设为 <code>150</code>秒或更长。</td></tr><tr><td><code>device</code></td><td>字符串</td><td>设备模拟： <code>"desktop"</code> （默认）或 <code>"mobile"</code>.</td></tr></tbody></table>

### 常见响应代码

<table><thead><tr><th width="112">状态</th><th width="322">含义</th><th>是否重试？</th></tr></thead><tbody><tr><td><code>200</code> / <code>202</code></td><td>成功。已接受 Realtime / 异步任务</td><td>–</td></tr><tr><td><code>400</code></td><td>请求格式错误</td><td>否，请修正 <code>errors[].pointer</code>.</td></tr><tr><td><code>401</code></td><td>身份验证错误（API 密钥无效或缺失）。</td><td>否，请检查 Web API 实例上的密钥</td></tr><tr><td><code>429</code></td><td>速率限制或配额已用尽</td><td>速率限制：有，需采用退避策略。配额限制：无。</td></tr><tr><td><code>5xx</code></td><td>上游故障或抓取失败</td><td>是，最多约重试 3 次，并采用退避策略。</td></tr></tbody></table>

查看所有 [响应代码](https://developers.oxylabs.io/products/web-api/troubleshooting) ，了解所有状态代码并查看故障排除提示。

## 后续步骤

* **正在构建您的第一个自定义请求？** 使用 [Web API Playground](https://developers.oxylabs.io/products/web-api/playground).
* **需要从特定网站获取数据？** 查看所有 Web API [专用爬虫](https://developers.oxylabs.io/products/web-api/scrape/dedicated-scrapers).
* **需要公司数据？** 通过关键词获取结构化公司简介，使用 [公司搜索](https://developers.oxylabs.io/products/web-api/search/companies).
* **想从任意页面获取结构化 JSON？** 试试 Web API 内置的 [AI 解析](https://developers.oxylabs.io/products/web-api/scrape/ai-parsing).
* **需要大规模抓取数据或将数据传输到云存储？** 了解可用的 [交付模式](https://developers.oxylabs.io/products/web-api/scrape/delivery-modes).
* **想让 AI 代理在无需编写代码的情况下使用 Web API？** 试试 Oxylabs 官方 [MCP 服务器](https://developers.oxylabs.io/ai-workflows/mcp) 或 [代理技能](https://developers.oxylabs.io/ai-workflows/agent-skills).


---

# 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://developers.oxylabs.io/documentation/cn/kai-shi-shi-yong/kuai-su-kai-shi-web-api.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.
