> 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/products/cn/web-api.md).

# Web API

了解如何使用和集成 Oxylabs Web API——一个用于网页搜索和页面数据采集的一体化 REST API。

Oxylabs Web API 通过统一的 REST 接口为应用和 AI 代理提供对开放网络的实时访问。它通过不同的端点处理 JavaScript 渲染、机器人流量挑战、代理轮换和地理定位，以适配不同的网页数据获取阶段：

<table><thead><tr><th width="106">端点</th><th width="504">用于</th><th width="148">输入</th></tr></thead><tbody><tr><td><a href="/products/cn/web-api/search.md">/search</a></td><td>发现并对自然搜索结果排序。</td><td>关键词 / 查询</td></tr><tr><td><a href="/products/cn/web-api/scrape.md">/scrape</a></td><td>将页面数据渲染并提取为 Markdown、HTML、JSON 或截图。</td><td>页面 URL</td></tr></tbody></table>

{% hint style="success" %}
Web API 端点设计为一起使用： **search 用于查找，scrape 用于读取。** `/search` 描述只是摘要，因此任何需要准确的信息都来自 `/scrape`.
{% endhint %}

## 使用方法

### 获取 API 密钥

在 [Oxylabs 控制台](https://dashboard.oxylabs.io)，创建一个 **Web API** 实例，然后从产品实例获取 API 密钥，并将其导出到项目环境中（例如你的 OS 终端或项目工作区中的 CLI 终端）：

```bash
export OXYLABS_WEB_API_KEY=your_api_key_here
```

参见 [身份验证](/products/cn/web-api/shen-fen-yan-zheng.md) 了解密钥管理和轮换。

### 选择集成方式

* **要将其接入 AI 代理（Claude Code、Cursor 或你自己的代理）吗？**\
  查看 [AI 代理集成](#ai-agent-integration) 即可通过一条命令开始使用。
* **要构建你自己的集成吗？**\
  请按照以下步骤，直接使用 REST 端点进行集成。

### 手动集成

{% stepper %}
{% step %}

#### 搜索

{% tabs %}
{% tab title="cURL" %}

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

{% endtab %}

{% tab title="Python" %}

```python
import os, requests

resp = requests.post(
    "https://webapi.oxylabs.io/v1/search",
    headers={"Authorization": f"Bearer {os.environ['OXYLABS_WEB_API_KEY']}"},
    json={"query": "eu ai act compliance deadlines", "max_results": 3},
    timeout=120,
)
resp.raise_for_status()

for r in resp.json()["results"]:
    print(r["metadata"]["position"], r["title"], r["url"], sep=" | ")
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const res = await fetch("https://webapi.oxylabs.io/v1/search", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.OXYLABS_WEB_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ query: "eu ai act compliance deadlines", max_results: 3 }),
});
if (!res.ok) throw new Error(`${res.status} ${await res.text()}`);

const { results } = await res.json();
results.forEach((r) => console.log(r.metadata.position, r.title, r.url));
```

{% endtab %}
{% endtabs %}

**输出示例**

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

参见 [/search](/products/cn/web-api/search.md) 有关请求参数和输出字典。
{% endstep %}

{% step %}

#### 抓取

读取由 `/search` 或你的 URL 列表：

{% tabs %}
{% tab title="cURL" %}

```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"]
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
page = requests.post(
    "https://webapi.oxylabs.io/v1/scrape",
    headers={"Authorization": f"Bearer {os.environ['OXYLABS_WEB_API_KEY']}"},
    json={
        "url": "https://artificialintelligenceact.eu/implementation-timeline/",
        "output": ["markdown"],
    },
    timeout=120,
)
page.raise_for_status()
print(page.json()["results"][0]["markdown"][:2000])
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const page = await fetch("https://webapi.oxylabs.io/v1/scrape", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.OXYLABS_WEB_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    url: "https://artificialintelligenceact.eu/implementation-timeline/",
    output: ["markdown"],
  }),
});
if (!page.ok) throw new Error(`${page.status} ${await page.text()}`);

const { results } = await page.json();
console.log(results[0].markdown.slice(0, 2000));
```

{% endtab %}
{% endtabs %}

参见 [/scrape](/products/cn/web-api/scrape.md) 有关请求参数、输出字典、交付模式。
{% endstep %}

{% step %}

#### 组合：search-to-scrape

搜索摘要（`outline`）已被截断，不足以进行深入分析或 LLM 流水线。标准集成模式会查询 `/v1/search` 以发现权威链接，然后将这些 URL 路由到 `/v1/scrape` ，请求 Markdown 输出以去除不必要的 HTML 产物。

下面的 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},
        timeout=120,
    )
    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 %}

### AI 代理集成

将 Web API 直接连接到 AI 框架、编码助手（Cursor、Claude Code）或自定义代理。

#### 选项 1：集成提示词

将以下完整提示词粘贴到 AI 编码代理（Claude Code、Cursor、Copilot）中，指导它根据我们的技术规范构建自定义集成：

{% code expandable="true" %}

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

阅读 https://developers.oxylabs.io/products/web-api/for-agents.md 并遵循
它。该页面包含基础 URL、认证、两个端点的模式、参考代码、错误和重试
规则，以及需要满足的清单。如果页面无法加载，停止并告诉我；不要
凭记忆重建 API。

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

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

在编写测试之前先证明它有效：执行一次真实搜索，从
结果中抓取一个 URL，并向我展示两个 request id。如果调用返回 401，停止并告诉我。

当 scrape 返回为空或内容过少时，使用 run_js: true 重试一次。如果仍然
为空且站点位于国家/地区 TLD（.lt、.es、.co.uk），再使用 run_js 和
将 location 设为该国家/地区后再重试一次，然后报告该页面不可读。

然后针对重试和错误映射添加一个测试，并使用模拟传输运行它。
如果你无法在此环境中运行命令，只说一次，并给我确切的
替代命令。

汇报：你采取的路径、页面上每个清单项标记为完成或未完成，
我还需要自己做什么，以及你未能完成的任何内容。不要问我
是否继续；直接执行。
```

{% endcode %}

该提示词将代理指向一个包含完整产品事实来源的单页：基础 URL、授权、两个端点模式、参考代码、错误和重试规则，以及代理清单。

你可以在 [面向代理](/products/cn/web-api/for-agents.md) 。

{% hint style="info" %}
**如果代理无法获取 URL**，那就把完整页面提供给它。 `for-agents.md` 是纯 Markdown 且自包含，因此可以先保存它，或将其粘贴到上面的提示词中，并删除提到该 URL 的段落。将规范本身排除在提示词之外：之所以在那里重复两条重试规则，是因为代理会在任务中途应用它们，其余内容都应放在页面上，以免偏离。
{% endhint %}

#### 选项 2：代理技能

安装官方代理技能，向你的 AI 代理教授研究方法、来源引用规则以及 search-to-scrape 执行：

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

有关更多安装选项，请参见 [Oxylabs Agent Skills](https://developers.oxylabs.io/ai-workflows/agent-skills).

#### 选项 3：MCP server

对于更精简且可控的实现，请自托管我们的官方 MCP server，以向任何兼容 MCP 的客户端暴露 **search**, **scrape**和 **extraction** 工具给任何兼容 MCP 的客户端：

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

有关配置细节和工具定义，请参见 [MCP 服务器](https://developers.oxylabs.io/ai-workflows/mcp).

#### 技能还是 MCP？

<table data-header-hidden><thead><tr><th width="210"></th><th></th><th></th></tr></thead><tbody><tr><td></td><td><a href="https://developers.oxylabs.io/ai-workflows/agent-skills"><strong>技能</strong></a></td><td><a href="https://developers.oxylabs.io/ai-workflows/mcp"><strong>MCP 服务器</strong></a></td></tr><tr><td>为代理提供</td><td>判断力：何时搜索、信任哪些来源、如何引用</td><td>可直接调用的类型化工具</td></tr><tr><td>需要一个运行中的进程</td><td>否</td><td>是</td></tr><tr><td>适用于</td><td>加载技能目录的代理</td><td>任何 MCP 客户端</td></tr></tbody></table>

同时安装两者也是一种选择。该 server 捆绑了 `oxylabs-web-api` 并将其作为 `oxylabs://skill/web-api` 资源，因此仅连接它就能为代理提供两部分功能。如果你想在没有运行中 server 的情况下使用它们，或者想将你的代码库迁移到 Oxylabs，请单独安装技能。

## 了解更多

<table data-header-hidden><thead><tr><th width="170"></th><th></th></tr></thead><tbody><tr><td><a href="/products/cn/web-api/shen-fen-yan-zheng.md"><strong>身份验证</strong></a></td><td>密钥处理、请求头要求和身份验证故障排查。</td></tr><tr><td><a href="/products/cn/web-api/search.md"><strong>搜索</strong></a></td><td>以下内容的完整请求参数和响应模式： <code>/v1/search</code>.</td></tr><tr><td><a href="/products/cn/web-api/scrape.md"><strong>抓取</strong></a></td><td>以下内容的请求参数和输出字典： <code>/v1/scrape</code>.</td></tr><tr><td><a href="/products/cn/web-api/scrape/zhuan-yong-pa-chong.md"><strong>专用抓取器</strong></a></td><td>面向特定目标的解析端点（Google、Amazon、YouTube、Walmart 等）。</td></tr><tr><td><a href="/products/cn/web-api/scrape/jiao-fu-mo-shi.md"><strong>交付模式</strong></a></td><td>Realtime 调用、异步单任务轮询/Webhook，以及批量队列。</td></tr><tr><td><a href="/products/cn/web-api/scrape/ai-jie-xi.md"><strong>AI 解析</strong></a></td><td>使用自然语言提示词或 JSON Schema 提取结构化 JSON。</td></tr><tr><td><a href="/products/cn/web-api/gu-zhang-pai-chu.md"><strong>故障排查</strong></a></td><td>HTTP 状态码、重试逻辑和故障排查提示。</td></tr></tbody></table>


---

# 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/products/cn/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.
