> 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-scraper-api/features/custom-parser/getting-started.md).

# 入门

## 如何使用自定义解析器 <a href="#how-to-use-custom-parser" id="how-to-use-custom-parser"></a>

### 场景示例

假设你想解析 **结果总数** Bing Search 使用搜索词返回的 `test`:

<figure><img src="/files/7e943bc0f43515cebbaae155f2f76a1600d7531f" alt=""><figcaption></figcaption></figure>

我们将概述实现这一目标的三种主要方法：

* [使用 OxyCopilot 生成解析器](#generate-parsers-with-oxycopilot)
* [通过 API 生成解析器](#generate-parsers-via-api)
* [手动编写解析指令](#write-instructions-manually)

### 使用 OxyCopilot 生成解析器

OxyCopilot 让你用简单的英文描述需求，以便 **自动为网站创建爬虫和解析器** 。按照以下步骤了解基础用法，并查看 [OxyCopilot 文档](/products/cn/web-scraper-api/web-scraper-api-playground/oxycopilot.md#custom-parser-builder) 了解更多信息。

{% hint style="success" %}
再次打开 [**网页爬虫API Playground**](https://dashboard.oxylabs.io/en/api-playground) 在我们的仪表板中访问 OxyCopilot。
{% endhint %}

{% stepper %}
{% step %}

#### 输入 URL

点击 **OxyCopilot 按钮** 左上角的，并输入最多 3 个相同页面类型的 URL。我们使用这个 Bing Search URL： `https://www.bing.com/search?q=test`.

<figure><img src="/files/7380edf9dbcef2de59de341bc9e49d5085988e66" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
你也可以通过填写 **网站**, **爬虫**、 **URL** 顶部的字段，并调整 **附加参数** （如左侧菜单中的 JavaScript 渲染）来手动配置爬虫。
{% endhint %}
{% endstep %}

{% step %}

#### 设置爬虫参数

接下来，指定爬虫参数、浏览器指令，并在目标网站需要时启用 JavaScript 渲染。

对于 Bing Search， **启用 JavaScript 渲染** 然后点击 **下一步**.

<figure><img src="/files/2d206ce72d4aff76ec5599ae21cc0a556e4d860f" alt="" width="375"><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### 编写提示词

说明你想从页面提取的数据。确保描述清楚并提供最重要的信息。你可以在我们的 [OxyCopilot 提示词库](https://oxylabs.io/resources/prompts-code-samples).

粘贴以下提示词，以从 Bing Search 页面提取结果总数：

```
解析搜索结果总数。
```

<figure><img src="/files/9a11dde303f6d083cb3e2068c544ab03d082c61b" alt="" width="563"><figcaption></figcaption></figure>

点击 **生成指令** 按钮以发送你的提示词。
{% endstep %}

{% step %}

#### 查看解析后的数据和指令

OxyCopilot 完成后，你会看到如下窗口，右侧显示解析后的数据：

<figure><img src="/files/0778153dbf952c3cc1bbeb0c5c5b8fa0f04a4ad3" alt=""><figcaption></figcaption></figure>

如果你想进行任何调整，可以在这里操作。修改 URL、优化提示词、启用 JavaScript 渲染，或 [编辑解析 schema](/products/cn/web-scraper-api/web-scraper-api-playground/oxycopilot.md#step-2-optional-adjust-parsing-schema) 以满足你的需求。当你更新此窗口中的任何字段时，可以通过选择 **开始新请求**.

你也可以 **查看并直接编辑解析指令** 在这里：

<figure><img src="/files/d9086a26611d7ad5f503a560ed9a0cb3d971bc7d" alt="" width="373"><figcaption></figcaption></figure>

当你对结果满意后， **加载指令** 以继续。
{% endstep %}

{% step %}

#### 将解析器保存为预设

你可以轻松将解析指令保存为 [解析器预设](/products/cn/web-scraper-api/features/custom-parser/parser-presets.md)。这样你就可以在 OxyCopilot 和 API 请求中重复使用该预设。&#x20;

在 网页爬虫API Playground 中，你还可以选择要为其保存预设的用户。全部设置完成后，只需点击 **保存**:

<figure><img src="/files/4087d095aba7e5f939d397e1bfcbe2d346eb64e0" alt=""><figcaption></figcaption></figure>

将出现一个弹窗，提示你为预设命名并添加可选描述：

<figure><img src="/files/99373eaed3c0428667fc6cf2844765278264d523" alt="" width="375"><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### 在 API 请求中使用预设

要在 网页爬虫API 请求中使用预设，请设置 `parse` 到 `true` 并使用以下项指定预设名称： `parser_preset` 参数。

**端点：** `POST https://data.oxylabs.io/v1/queries`

```json
{
    "source": "bing_search",
    "query": "test",
    "render": "html",
    "parse": true,
    "parser_preset": "Bing_total_results"
}
```

运行请求后将返回以下 JSON 输出：

```json
{
    "results": [
        {
            "content": {
                "parse_status_code": 12000,
                "total_search_results": 12000000
            },
            "created_at": "2025-10-24 09:29:28",
            "updated_at": "2025-10-24 09:30:42",
            "page": 1,
            "url": "https://www.bing.com/search?q=test",
            "job_id": "7387419953164488705",
            "is_render_forced": false,
            "status_code": 200,
            "type": "parsed",
            "parser_type": "preset",
            "parser_preset": "Bing_total_results"
        }
    ]
}
```

{% endstep %}
{% endstepper %}

## 高级用法

### 通过 API 生成解析器

你也可以不在 playground 中使用 OxyCopilot，而是直接向 网页爬虫API 发送提示词并生成解析器。参见 [通过 API 生成解析指令](/products/cn/web-scraper-api/features/custom-parser/generating-parsing-instructions-via-api.md) 文档页面以了解更多。

{% hint style="success" %}
我们建议 **提供 3-5 个相同类型的 URL** （例如商品页面）。这有助于解析器适应不同布局并提高解析准确性。
{% endhint %}

**端点：** `POST https://data.oxylabs.io/v1/parsers/generate-instructions/prompt`

```json
{
    "prompt_text": "Parse the number of total search results.",
    "urls": ["https://www.bing.com/search?q=test"],
    "render": true
}
```

<details>

<summary>输出</summary>

```json
{
    "parsing_instructions": {
        "total_search_results": {
            "_fns": [
                {
                    "_args": [
                        "//span[contains(@class, 'count')]/text()"
                    ],
                    "_fn": "xpath_one"
                },
                {
                    "_fn": "amount_from_string"
                }
            ]
        }
    },
    "prompt_schema": {
        "properties": {
            "total_search_results": {
                "description": "搜索结果总数。",
                "title": "搜索结果总数",
                "type": "number"
            }
        },
        "required": [
            "total_search_results"
        ],
        "title": "字段",
        "type": "object"
    }
}
```

</details>

### 通过 API 保存解析器预设

网页爬虫API 允许你将解析指令保存为可重复使用的解析器预设。查看 [解析器预设](/products/cn/web-scraper-api/features/custom-parser/parser-presets.md) 文档以获取可用操作列表和完整的代码示例。

**端点：** `POST https://data.oxylabs.io/v1/parsers/presets`

```json
{
    "name": "Bing_total_results",
    "parsing_instructions": {
        "total_search_results": {
            "_fns": [
                {
                    "_fn": "xpath_one",
                    "_args": [
                        "//span[contains(@class, 'count')]/text()"
                    ]
                },
                {
                    "_fn": "amount_from_string"
                }
            ]
        }
    }
}
```

<details>

<summary>输出</summary>

```json
{
    "id": 421938,
    "name": "Bing_total_results",
    "description": null,
    "prompt_text": null,
    "prompt_schema": null,
    "urls": [],
    "render": false,
    "parsing_instructions": {
        "total_search_results": {
            "_fns": [
                {
                    "_args": [
                        "//span[contains(@class, 'count')]/text()"
                    ],
                    "_fn": "xpath_one"
                },
                {
                    "_fn": "amount_from_string"
                }
            ]
        }
    },
    "self_heal": false,
    "heal_status": "disabled",
    "last_healed_at": null,
    "created_at": "2025-10-27 09:28:37",
    "updated_at": "2025-10-27 09:28:37"
}
```

</details>

### 手动编写指令

要手动使用自定义解析器，请在创建任务时包含一组 `parsing_instructions` 。你可以使用 **CSS 和 XPath 选择器** 来定位 DOM 中的元素。

按照下面的分步示例学习基础知识，然后查看我们关于 [手动编写指令](/products/cn/web-scraper-api/features/custom-parser/writing-instructions-manually.md) 的深入指南，了解高级技巧和详细文档。

我们以 Bing Search 场景为例。任务参数如下所示：

```json
{
    "source": "bing_search",
    "query": "test",
    "render": "html",
    "parse": true,
    "parsing_instructions": {
        "number_of_results": {
            "_fns": [
                {
                    "_fn": "xpath_one",
                    "_args": [".//span[@class='sb_count']/text()"]
                }
            ]
        }
    }
}
```

**步骤 1。** 您必须提供 `"parse": true` 参数。

**步骤 2。** 解析指令必须在 `"parsing_instructions"` 字段中描述。

上面的解析指令示例指定，目标是从抓取的文档中解析搜索结果数量，并将结果放入 `number_of_results` 字段中。通过定义“pipeline”来解析该字段的指令如下：

```json
"_fns": [
    {
        "_fn": "xpath_one",
        "_args": [".//span[@class='sb_count']/text()"]
    }
]
```

该 pipeline 描述了一个要执行的数据处理函数列表。函数会按照列表中的出现顺序执行，并将前一个函数的输出作为后一个函数的输入。&#x20;

在上面的示例 pipeline 中，使用了 `xpath_one` 函数（[可用函数完整列表](/products/cn/web-scraper-api/features/custom-parser/writing-instructions-manually/list-of-functions.md)）。它允许你使用 XPath 表达式和 XSLT 函数处理 HTML 文档。作为函数参数，请指定可找到目标元素的准确路径： `.//span[@class='sb_count']`。你也可以指示解析器选择目标元素中的 `text()` 。

上面示例任务的解析结果应如下所示：

```json
{
    "results": [
        {
            "content": {
                "number_of_results": "About 16,700,000 results",
                "parse_status_code": 12000
            },
            "created_at": "2025-10-27 09:48:04",
            "updated_at": "2025-10-27 09:48:38",
            "page": 1,
            "url": "https://www.bing.com/search?q=test",
            "job_id": "7388511797231226881",
            "is_render_forced": false,
            "status_code": 200,
            "type": "parsed",
            "parser_type": "custom",
            "parser_preset": null
        }
    ]
}
```

自定义解析器不仅可以从抓取的 HTML 中提取文本，还可以执行基础数据处理函数。&#x20;

例如，前面描述的解析指令提取的是 `number_of_results` ，其文本中带有你未必需要的额外关键词。如果你想获取给定 `query=test` 的结果数量，并以数值数据类型返回，你可以复用相同的解析指令并添加 `amount_from_string` 函数到现有 pipeline 中：

```json
{
    "source": "bing_search",
    "query": "test",
    "render": "html",
    "parse": true,
    "parsing_instructions": {
        "number_of_results": {
            "_fns": [
                {
                    "_fn": "xpath_one",
                    "_args": [".//span[@class='sb_count']/text()"]
                },
                {
                    "_fn": "amount_from_string"
                }
            ]
        }
    }
}
```

上面示例任务的解析结果应如下所示：

```json
{
    "results": [
        {
            "content": {
                "number_of_results": 14200000,
                "parse_status_code": 12000
            },
            "created_at": "2025-10-27 10:00:36",
            "updated_at": "2025-10-27 10:01:05",
            "page": 1,
            "url": "https://www.bing.com/search?q=test",
            "job_id": "7388514950961963009",
            "is_render_forced": false,
            "status_code": 200,
            "type": "parsed",
            "parser_type": "custom",
            "parser_preset": null
        }
    ]
}
```

## 使用自定义解析器时，如果解析失败会发生什么 <a href="#what-happens-if-parsing-fails-when-using-custom-parser" id="what-happens-if-parsing-fails-when-using-custom-parser"></a>

如果自定义解析器无法处理客户端定义的解析指令，我们将返回 `12005` 状态码（已解析但有警告）。

```json
{
    "source": "bing_search",
    "query": "test",
    "render": "html",
    "parse": true,
    "parsing_instructions": {
        "number_of_results": {
            "_fns": [
                {
                    "_fn": "xpath_one",
                    "_args": [".//span[@class='sb_count']/text()"]
                },
                {
                    "_fn": "amount_from_string"
                }
            ]
        },
        "number_of_organics": {
            "_fns": [
                {
                    "_fn": "xpath",
                    "_args": ["//this-will-not-match-anything"]
                },
                {
                    "_fn": "length"
                }
            ]
        }
    }
}
```

你仍会为这类结果付费：

```json
{
    "results": [
        {
            "content": {
                "_warnings": [
                    {
                        "_fn": "xpath",
                        "_msg": "XPath expressions did not match any data.",
                        "_path": ".number_of_organics",
                        "_fn_idx": 0
                    }
                ],
                "number_of_results": 14200000,
                "parse_status_code": 12005,
                "number_of_organics": null
            },
            "created_at": "2025-10-27 10:03:54",
            "updated_at": "2025-10-27 10:04:22",
            "page": 1,
            "url": "https://www.bing.com/search?q=test",
            "job_id": "7388515782126234625",
            "is_render_forced": false,
            "status_code": 200,
            "type": "parsed",
            "parser_type": "custom",
            "parser_preset": null
        }
    ]
}
```

如果自定义解析器在解析过程中遇到异常并中断，可能会返回以下状态码： `12002`, `12006`, `12007`。这些意外错误不会向你收费。

## 状态码 <a href="#status-codes" id="status-codes"></a>

查看我们列出的状态码 [**此处**](/products/cn/web-scraper-api/response-codes.md#parsers).


---

# 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:

```
GET https://developers.oxylabs.io/products/cn/web-scraper-api/features/custom-parser/getting-started.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
