> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-zh.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# Apify 数据集集成

> 使用 LangChain Python 与 Apify 数据集文档加载器集成。

> [Apify 数据集](https://docs.apify.com/platform/storage/dataset) 是一个可扩展的仅追加存储，支持顺序访问，专为存储结构化网络爬取结果（如产品列表或 Google 搜索结果页面）而设计，并可将它们导出为 JSON、CSV 或 Excel 等多种格式。数据集主要用于保存 [Apify Actors](https://apify.com/store) 的结果——这些是无服务器云程序，适用于各种网络爬取、抓取和数据提取用例。

本笔记本展示了如何将 Apify 数据集加载到 LangChain 中。

### 集成详情

| 类                                                                | 包                                                              | 可序列化 | [JS 支持](https://js.langchain.com/docs/integrations/document_loaders/web_loaders/apify_dataset) |                                               版本                                              |
| :--------------------------------------------------------------- | :------------------------------------------------------------- | :--: | :--------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------: |
| [`ApifyDatasetLoader`](https://github.com/apify/langchain-apify) | [`langchain-apify`](https://pypi.org/project/langchain-apify/) |   ❌  |                                                ✅                                               | ![PyPI - Version](https://img.shields.io/pypi/v/langchain-apify?style=flat-square\&label=%20) |

### 加载器特性

|     来源    | 文档惰性加载 | 原生异步支持 |
| :-------: | :----: | :----: |
| Apify 数据集 |    ❌   |    ❌   |

## 前提条件

您需要在 Apify 平台上拥有一个现有的数据集。本示例展示了如何加载由 [网站内容爬虫](https://apify.com/apify/website-content-crawler) 生成的数据集。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
pip install -qU langchain langchain-apify langchain-openai
```

首先，将 `ApifyDatasetLoader` 导入到您的源代码中：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_apify import ApifyDatasetLoader
from langchain_core.documents import Document
```

找到您的 [Apify API 令牌](https://console.apify.com/account/integrations) 和 [OpenAI API 密钥](https://platform.openai.com/account/api-keys)，并将它们初始化为环境变量：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import os

os.environ["APIFY_TOKEN"] = "your-apify-token"
os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
```

## 定价

Apify Actors 的定价方式可能不同，具体取决于您运行的 Actor。
许多 Actor 支持 [按事件付费 (PPE) 定价](https://docs.apify.com/platform/actors/publishing/monetize/pay-per-event)，即您为 Actor 作者定义的明确事件（例如，每个数据集项）付费。这对于希望获得清晰、按操作计费的代理工作负载来说可能是一个不错的选择。

## 将数据集项映射到文档

接下来，定义一个函数，将 Apify 数据集记录字段映射到 LangChain [`Document`](https://reference.langchain.com/python/langchain-core/documents/base/Document) 格式。

例如，如果您的数据集项结构如下：

```json theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{
    "url": "https://apify.com",
    "text": "Apify is the best web scraping and automation platform."
}
```

下面代码中的映射函数会将它们转换为 LangChain [`Document`](https://reference.langchain.com/python/langchain-core/documents/base/Document) 格式，以便您可以进一步与任何 LLM 模型（例如用于问答）一起使用。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
loader = ApifyDatasetLoader(
    dataset_id="your-dataset-id",
    dataset_mapping_function=lambda dataset_item: Document(
        page_content=dataset_item["text"], metadata={"source": dataset_item["url"]}
    ),
)
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
data = loader.load()
```

## 一个问答示例

在此示例中，我们使用数据集中的数据来回答问题。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain.indexes import VectorstoreIndexCreator
from langchain_apify import ApifyWrapper
from langchain_core.documents import Document
from langchain_core.vectorstores import InMemoryVectorStore
from langchain_openai import ChatOpenAI
from langchain_openai.embeddings import OpenAIEmbeddings
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
loader = ApifyDatasetLoader(
    dataset_id="your-dataset-id",
    dataset_mapping_function=lambda item: Document(
        page_content=item["text"] or "", metadata={"source": item["url"]}
    ),
)
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
index = VectorstoreIndexCreator(
    vectorstore_cls=InMemoryVectorStore, embedding=OpenAIEmbeddings()
).from_loaders([loader])
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
llm = ChatOpenAI(model="gpt-5-mini")
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
query = "What is Apify?"
result = index.query_with_sources(query, llm=llm)
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
print(result["answer"])
print(result["sources"])
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
 Apify is a platform for developing, running, and sharing serverless cloud programs. It enables users to create web scraping and automation tools and publish them on the Apify platform.

https://docs.apify.com/platform/actors, https://docs.apify.com/platform/actors/running/actors-in-store, https://docs.apify.com/platform/security, https://docs.apify.com/platform/actors/examples
```

***

## 使用 Apify MCP 服务器

不确定使用哪个 Actor 或其需要哪些参数？[Apify MCP（模型上下文协议）服务器](https://mcp.apify.com) 可以帮助您发现可用的 Actors、探索其输入模式并了解参数要求。

通过 HTTP 连接到 Apify MCP 服务器时，请在请求头中包含您的 Apify 令牌：

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
Authorization: Bearer <APIFY_TOKEN>
```

更多信息，请参阅 [LangChain MCP 文档](/oss/python/langchain/mcp)。

***

<div className="source-links">
  <Callout icon="edit">
    [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/i18n\zh-CN\oss\python\integrations\document_loaders\apify_dataset.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
  </Callout>

  <Callout icon="terminal-2">
    [Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers.
  </Callout>
</div>
