# 入门

## 如何使用自定义解析器 <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(s)

点击 **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 渲染，或 [编辑解析架构](/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 请求中使用预设，请设置 `解析` 到 `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,
            "类型": "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": "解析搜索结果总数。",
    "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` 字段中。通过定义“管道”来解析该字段的指令如下：

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

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

在上面的示例管道中， `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": "约 16,700,000 条结果",
                "解析状态码": 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,
            "类型": "parsed",
            "parser_type": "custom",
            "parser_preset": null
        }
    ]
}
```

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

例如，前面描述的解析指令提取了 `number_of_results` ，作为带有您未必需要的额外关键词的文本。如果您想获取给定 `query=test` 的结果数量，并以数值数据类型表示，您可以重用相同的解析指令并添加 `amount_from_string` 函数到现有管道中：

```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,
                "解析状态码": 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,
            "类型": "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 表达式未匹配到任何数据。",
                        "_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,
            "类型": "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: 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.
