> 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 文档](/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>

它们设计为协同使用： **用 search 查找，用 scrape 提取。** 本快速入门指南涵盖：

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

{% hint style="success" %}
想在正式实现前先在一个简单的基于 UI 的环境中测试 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`)

找出哪些页面包含你定义的 `查询`:

```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 %}

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

`大纲` 位于 `/search` 是一个被截断片段的列表，通常不适用于高级用例或 AI 工作流。

要通过单个查询获取结构化数据，请使用以下方式搜索网络： `/search` 根据你的 `查询` 并将结果 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. Discover target URLs
    hits = requests.post(
        f"{API}/v1/search",
        headers=HEADERS,
        json={"query": question, "max_results": 10},
    )
    hits.raise_for_status()
    # 2. Extract full page content as 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" %}
**上述内容都是实时的——结果会直接在响应中返回。** 对于大规模数据采集，我们建议将抓取器作为作业运行，使用 `/v1/async/scrape` 并通过轮询、回调或直接投递到你的 bucket 交付。参见 [交付方式](https://developers.oxylabs.io/products/web-api/scrape/delivery-modes).
{% endhint %}

### AI 代理集成

Oxylabs Web API 旨在通过以下方式轻松支持 AI 代理工作流： **Agent Skills**, **MCP** （Model Context Protocol）或简单的 **单提示集成**。拿到 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 并遵循
它。它包含 base URL、认证、两个端点模式、参考代码、错误和重试
规则，以及需要满足的清单。如果页面无法加载，请停止并告诉我；不要
仅凭记忆重建 API。

在编写任何内容前，先确定方案并告诉我：
这个项目自身的代码会在运行时调用 API 吗？-> 编写页面指定的客户端
  所描述的内容，并保持与此代码库现有的外发 HTTP 调用方式一致。
本次会话中的网络访问是供你使用，而不是供项目代码使用吗？
  -> 按页面说明安装 MCP server 和 skills。

密钥位于 OXYLABS_WEB_API_KEY 或此处的 .env 中。如果两者都不在，请问我。绝不要
打印该密钥：不要出现在代码、日志、测试或你给我的回复中。

在编写测试前先证明它可用：执行一次真实搜索，从
结果中抓取一个 URL，并把两个 request 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="Agent Skills" icon="head-side-gear" %}
**Agent skills——安装关于如何使用 API 的知识，无需运行 server。**

使用以下终端命令添加官方 agent skills，教你的 AI 代理如何通过 Oxylabs Web API 进行搜索、抓取、引用来源并处理网络研究：

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

现在你的代理已经了解 Oxylabs Web API 及其使用方法。要了解更多 Web API agent skills，请参见我们的 [文档](https://developers.oxylabs.io/ai-workflows/agent-skills).
{% endtab %}

{% tab title="MCP Server" icon="server" %}
**MCP server——为任何 MCP client 提供带类型的搜索、抓取和专用抓取工具。**

自行托管我们的官方 MCP server，直接将 Web API 的搜索、抓取和提取工具暴露给 Claude Code、Cursor 或你的自定义 AI 代理：

```bash
uv tool install git+https://github.com/oxylabs/web-api-mcp
```

要了解更多 Web API MCP 集成，请参见 [MCP server](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>查询</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>要抓取的 URL</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>用于通过提示词或 schema 进行自定义 AI 解析</td></tr><tr><td><code>location</code></td><td>字符串</td><td>两位国家代码（例如， <code>"DE"</code>, <code>"US"</code>）。某些专用抓取器使用不同格式。参见 <a href="/products/cn/web-api/scrape/zhuan-yong-pa-chong.md">Dedicated Scrapers</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 文档](https://developers.oxylabs.io/products/web-api).
* **正在构建你的第一个自定义请求吗？** 使用以下内容更快完成原型设计： [Web API Playground](https://developers.oxylabs.io/products/web-api/playground).
* **需要来自特定网站的数据吗？** 查看所有 Web API [Dedicated Scrapers](https://developers.oxylabs.io/products/web-api/scrape/dedicated-scrapers).
* **想从任意页面获取结构化 JSON 吗？** 试试 Web API 内置的 [AI Parsing](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 server](https://developers.oxylabs.io/ai-workflows/mcp) 或 [Agent Skills](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.
