> 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/for-agents.md).

# 供代理使用

AI 智能体集成 Oxylabs Web API 所需的一切，尽在一页。

**安装比构建更简单。** 如果此项目还没有代码，或者访问 Web 是为了 *你* 而不是为了项目自身的代码，那么整个任务只需运行一条命令：

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

这会安装 skills； [MCP 服务器](https://developers.oxylabs.io/ai-workflows/mcp) 会添加类型化工具，而两者 [可以结合使用](https://developers.oxylabs.io/products/cn/web-api.md#skills-or-mcp). 当 *项目* 的代码需要自行发起请求时，可根据本页构建客户端——所需内容如下。

## 你将获得什么

两个端点，位于 `https://webapi.oxylabs.io`:

<table><thead><tr><th width="168">端点</th><th>返回内容</th><th>用途</th></tr></thead><tbody><tr><td><code>POST /v1/search</code></td><td>按排名排序的结果：标题、摘要、URL</td><td>查找包含答案的页面</td></tr><tr><td><code>POST /v1/scrape</code></td><td>单个页面的内容</td><td>读取页面，包括依赖大量 JavaScript 和受机器人防护的页面</td></tr></tbody></table>

**核心模式是搜索 → 抓取。** 搜索会告诉你答案在哪里；抓取则会获取答案。搜索摘要经过截断，而且往往已经过时——它们用于定位来源，不能代替来源本身。

**公司搜索是个例外。** `/v1/search/companies` 会直接返回数据，因此无需再抓取。问题涉及公司时（例如谁在某个行业运营、公司规模有多大），请使用此端点；其他情况使用 `/v1/search` 。

## 身份验证

每次调用都发送 `Authorization: Bearer $OXYLABS_WEB_API_KEY` 。如果未设置此变量， **请停止操作并向用户索取密钥** ——不要编造密钥，也不要退而改用未经身份验证的方式抓取网页。一个看似有效却 `401`失败的密钥通常属于其他 Oxylabs 产品。请参阅 [身份验证](https://developers.oxylabs.io/products/cn/web-api/shen-fen-yan-zheng.md).

## `POST /v1/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": 5}'
```

<table><thead><tr><th width="123">字段</th><th width="81">类型</th><th width="83">必填</th><th width="73">默认值</th><th>约束</th></tr></thead><tbody><tr><td><code>query</code></td><td>字符串</td><td>是</td><td>—</td><td>1–2048 个字符</td></tr><tr><td><code>max_results</code></td><td>整数</td><td>否</td><td><code>10</code></td><td>1–20</td></tr><tr><td><code>location</code></td><td>字符串</td><td>否</td><td><code>null</code></td><td>ISO 3166-1 alpha-2 国家/地区代码，例如 <code>"DE"</code>, <code>"US"</code></td></tr></tbody></table>

不接受未知字段，而不是忽略它们。响应（`200`) — `state` 为 `done`，且数组始终存在；为空表示没有匹配项：

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

## `POST /v1/scrape`

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

<table><thead><tr><th width="102">字段</th><th width="89">类型</th><th width="82">必填</th><th>注释</th></tr></thead><tbody><tr><td><code>url</code></td><td>字符串</td><td>是</td><td>绝对 <code>http</code>/<code>https</code> URL</td></tr><tr><td><code>output</code></td><td>数组</td><td>否</td><td><code>["markdown"]</code>, <code>["html"]</code>, <code>["json"]</code>, <code>["screenshot"]</code>，或它们的组合；默认值 <code>["html"]</code>; <code>screenshot</code> 需要 <code>run_js: true</code></td></tr><tr><td><code>json</code></td><td>对象</td><td>否</td><td>以及 <code>output: ["json"]</code>, <code>{"prompt": "fields to extract"}</code></td></tr><tr><td><code>location</code></td><td>字符串</td><td>否</td><td>两字母国家代码，例如 <code>"DE"</code></td></tr><tr><td><code>device</code></td><td>字符串</td><td>否</td><td><code>"desktop"</code> 或 <code>"mobile"</code></td></tr><tr><td><code>run_js</code></td><td>布尔值</td><td>否</td><td>执行页面 JavaScript</td></tr></tbody></table>

请求 `output: ["markdown"]` 以便读取页面； `仅在需要标记本身时请求 ["html"]，并且` 仅在需要标记本身时，以及 `["json"]` 搭配 `json.prompt` 以指定字段。响应使用相同的封装结构： `results[]` 包含所请求格式的页面内容，以及最终的 `url` （重定向后）。请谨慎读取——字段会因目标和格式而异。

## 完整集成示例

```python
"""Oxylabs Web API 客户端：搜索、抓取，以及两者的研究循环。"""

import os
import random
import time

import requests

API = "https://webapi.oxylabs.io"
RETRYABLE = {408, 429, 500, 502, 503, 504}

class WebApiError(RuntimeError):
    pass

class AuthenticationError(WebApiError):
    pass

def _key() -> str:
    key = os.environ.get("OXYLABS_WEB_API_KEY", "").strip()
    if not key:
        raise WebApiError("OXYLABS_WEB_API_KEY is not set — ask the user for a key.")
    return key

def _post(path: str, payload: dict, attempts: int = 3) -> dict:
    headers = {"Authorization": f"Bearer {_key()}", "Content-Type": "application/json"}
    for attempt in range(1, attempts + 1):
        try:
            resp = requests.post(f"{API}{path}", json=payload, headers=headers, timeout=150)
        except requests.Timeout as exc:
            if attempt == attempts:
                raise WebApiError(f"{path} -> timed out after {attempts} attempts") from exc
            time.sleep(2**attempt + random.random())
            继续
        if resp.ok:
            return resp.json()
        if resp.status_code == 401:
            raise AuthenticationError("401 — the API key was rejected. Stop and tell the user.")
        if resp.status_code not in RETRYABLE or attempt == attempts:
            try:
                problem = resp.json()
                detail = f"{problem['title']}: {problem['detail']}"
            except (ValueError, KeyError):
                detail = resp.text[:300]
            raise WebApiError(f"{path} -> {resp.status_code}: {detail}")
        time.sleep(2**attempt + random.random())  # jitter: avoid lockstep retries
    raise WebApiError("unreachable")

def search(query: str, max_results: int = 10, location: str | None = None) -> list[dict]:
    payload = {"query": query, "max_results": max_results}
    if location:
        payload["location"] = location
    return _post("/v1/search", payload)["results"]

def scrape(url: str, fmt: str = "markdown", location: str | None = None) -> dict:
    payload: dict = {"url": url, "output": [fmt]}
    if location:
        payload["location"] = location
    results = _post("/v1/scrape", payload).get("results", [])
    if not results or results[0].get(fmt) is None:
        raise WebApiError(f"/v1/scrape -> no {fmt} result for {url}")
    return results[0]

def research(question: str, read_top: int = 2, location: str | None = None) -> list[dict]:
    """Search, then read the top results. Returns [{url, title, content}] with sources kept."""
    pages = []
    for hit in search(question, max_results=10, location=location)[:read_top]:
        try:
            page = scrape(hit["url"], location=location)
        except AuthenticationError:
            raise
        except WebApiError as exc:
            # A dead URL is a fact to report, not a reason to lose the other sources.
            pages.append({"url": hit["url"], "title": hit["title"], "error": str(exc)})
            继续
        pages.append({"url": hit["url"], "title": hit["title"], "content": page["markdown"]})
    return pages
```

## 错误

<table><thead><tr><th width="78">状态</th><th>含义</th><th>你的处理方式</th></tr></thead><tbody><tr><td><code>400</code></td><td>验证失败</td><td>读取 <code>errors[].pointer</code> 和 <code>errors[].detail</code>，修复这些字段。 <strong>切勿原样重试。</strong></td></tr><tr><td><code>401</code></td><td>凭据问题，而非请求字段问题：缺少密钥、格式错误的 <code>Authorization</code> 标头，或 API 拒绝的密钥。</td><td>停止。告知用户。重试无济于事。</td></tr><tr><td><code>408</code></td><td>抓取在服务器端超时</td><td>采用退避策略重试——请求未能得到结果。</td></tr><tr><td><code>429</code></td><td>速率限制 <strong>或</strong> 额度已用尽——响应正文会说明是哪种情况，但这是自然语言文本，因此不要根据它进行匹配</td><td>采用退避策略并降低并发数。限制总重试次数：如果完整经历退避后仍然失败，说明是用户的额度问题，不应继续重试。</td></tr><tr><td><code>5xx</code></td><td>上游暂时性故障</td><td>采用退避策略，最多重试 3 次。</td></tr></tbody></table>

失败时会使用适当的非`2xx` 状态码和 RFC 9457 问题正文。如果所有搜索引擎都失败， `/v1/search` 会以 `500` 和 `"state": "faulted"` 以及 `"title": "REQUEST_FAILED_AFTER_MANY_RETRIES"`作出响应；此请求不计费，因此应像对待任何 `5xx`错误一样重试，然后将错误呈现给用户。在 `results` 数组为空时， `200` 只表示没有匹配项。请参阅 [错误](https://developers.oxylabs.io/products/cn/web-api/gu-zhang-pai-cha.md).

错误代码位于 `title`中；应根据它进行分支判断，绝不要根据 `detail`:

```json
{
  "status": 400,
  "title": "VALIDATION_ERROR",
  "detail": "1 request field is invalid; fix every entry in `errors` and resend.",
  "instance": "6285041d-b00d8d69959c4b36f50fb53b",
  "metadata": { "timestamp": 1788762578, "request_id": "1788875675880097469" },
  "errors": [
    { "pointer": "#/max_results", "detail": "Input should be less than or equal to 20" }
  ]
}
```

将客户端超时设置为约 **150 秒**。抓取需要渲染真实页面；10 秒超时会导致本可成功的任务失败，而你仍需为此付费。

## 关键规则

| 规则                                                                                                                                                     | 原因                                     |
| ------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------- |
| 搜索用于查找，抓取用于阅读——先搜索一次，然后抓取可能包含答案的 1–3 个 URL                                                                                                             | 抓取全部十个 URL，成本会高出 5 倍，答案却更差             |
| 切勿依据 `outline`                                                                                                                                         | 内容在句子中途被截断，而且会丢掉改变含义的限定信息              |
| 读取页面时使用 `output: ["markdown"]`                                                                                                                         | 仅需处理 HTML 的一小部分词元，且保留其结构；在客户端转换是白费功夫   |
| 收集每条事实时，都将其对应的 URL 一并保存                                                                                                                                | 事后补上的引用正是错误归因的由来                       |
| 绝不要凭记忆填补空缺——应说明尚未确认                                                                                                                                    | 用回忆代替来源，会让集成失去可信度                      |
| 每次搜索只问一个问题                                                                                                                                             | 复合查询返回的结果可能两部分都不匹配                     |
| 传入 `location` （当答案涉及地理位置时）                                                                                                                             | 价格、可用性和排名因国家/地区而异；不注明国家/地区的答案总会在某些地方出错 |
| 抓取结果为空或只有少量内容：使用以下设置重试一次 `run_js: true`                                                                                                                | 页面在客户端渲染，而你拿到的只是页面框架；渲染速度较慢，因此不要默认启用   |
| 结果仍为空，且该网站使用国家/地区顶级域名：再重试一次，使用 `run_js: true` 以及 `location` 并将其设为对应国家/地区， `.lt` → `LT`, `.co.uk` → `GB`。跳过用于品牌的国家/地区顶级域名，例如 `.io`, `.ai`, `.co`, `.me` | 有些网站只面向本国提供服务；第三次尝试后，页面仍无法读取的话，请报告此情况。 |
| 为任何有时效性的内容标注日期                                                                                                                                         | 页面撰写时的价格、版本和排名                         |
| 明确报告失败                                                                                                                                                 | “抓取 X 失败”是一个真实结果；悄悄丢弃它则不是              |
| 不要在同一任务中重复抓取同一个 URL                                                                                                                                    | 按 URL 缓存                               |
| 将密钥保存在服务器端，不要放在源代码、日志或错误消息中                                                                                                                            | 它是一项可用于消费的凭证                           |

## 发现

不要对功能进行硬编码： `GET /v1/scrapers` 会列出已实现的抓取端点，并且 `OPTIONS` 在某个端点上调用时，会返回其参数及类型，因此无需更改代码即可提供新功能。请参阅 [发现](https://developers.oxylabs.io/products/cn/web-api/scrape/duan-dian-fa-xian.md).

该 `/search` 端点可能包含用于特定搜索的子端点（例如公司搜索）。请查阅 API 参考文档中的 [搜索端点](https://developers.oxylabs.io/api-reference/cn/company.md) 页面，确认可用选项。

## 集成检查清单

对于客户端分支——上述规则是判断标准，以下是具体实现：

* [ ] 密钥从此处读取 `OXYLABS_WEB_API_KEY`，绝不硬编码，也绝不记录到日志中
* [ ] `Authorization: Bearer` 标头需包含在每个请求中
* [ ] 客户端超时时间约为 150 秒
* [ ] 将任意 `2xx`状态视为成功，绝不使用字面值 `201`
* [ ] `query` 的长度不得超过 2048 个字符， `location` 应为 ISO 3166-1 alpha-2 国家/地区代码（向 `/v1/search/companies`)
* [ ] 不发送 location） `408`/`429`/`仅对传输超时和` 5xx
* [ ] `400`/`401` 错误进行重试，采用带抖动的指数退避，最多尝试约 3 次
* [ ] `将错误与字段名或清晰的错误消息一同呈现，不重试` search `端点的` max\_results
* [ ] `上限设为 ≤ 20` 记录
* [ ] metadata.request\_id，以便报告故障。测试会自行设置一个虚拟密钥，因此断言失败时打印的是虚拟密钥，而不是真实密钥。


---

# 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/for-agents.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.
