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

# Apify actor 集成

> 使用 LangChain Python 与 Apify actor 工具集成。

> [Apify Actors](https://docs.apify.com/platform/actors) 是为广泛的网页抓取、爬取和数据提取任务而设计的云程序。这些 actor 促进了从网络自动收集数据，使用户能够高效地提取、处理和存储信息。actor 可用于执行诸如抓取电子商务网站的产品详情、监控价格变化或收集搜索引擎结果等任务。它们与 [Apify Datasets](https://docs.apify.com/platform/storage/dataset) 无缝集成，允许将 actor 收集的结构化数据以 JSON、CSV 或 Excel 等格式存储、管理和导出，以供进一步分析或使用。

## 概述

本笔记本将引导您了解如何将 [Apify Actors](https://docs.apify.com/platform/actors) 与 LangChain 结合使用，以自动化网页抓取和数据提取。`langchain-apify` 包将 Apify 的云工具与 LangChain 代理集成，为 AI 应用程序实现高效的数据收集和处理。

### 集成详情

| 类                                                             | 包                                                              | 可序列化 | [JS 支持](https://js.langchain.com/docs/integrations/tools/apify_actors) |                                               版本                                              |
| :------------------------------------------------------------ | :------------------------------------------------------------- | :--: | :--------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------: |
| [`ApifyActorsTool`](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) |

### 工具特性

| 返回制品 | 原生异步 |         返回数据         |                     定价                     |
| :--: | :--: | :------------------: | :----------------------------------------: |
|   ❌  |   ✅  | Actor 输出（因 Actor 而异） | 按使用量付费，[提供免费层级](https://apify.com/pricing) |

## 设置

此集成位于 [langchain-apify](https://pypi.org/project/langchain-apify/) 包中。可以使用 pip 安装该包。

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

### 先决条件

* **Apify 账户**：注册您的免费 [Apify 账户](https://console.apify.com/sign-up)。
* **Apify API 令牌**：了解如何在 [Apify 文档](https://docs.apify.com/platform/integrations/api) 中获取您的 API 令牌。

```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 使用按使用量付费的定价模式，并提供免费层级。
定价因 Actor 而异——有些 Actor 是免费的（您只需支付平台使用费），而其他 Actor 则按结果或事件收费。

## 实例化

在这里，我们实例化 `ApifyActorsTool` 以便能够调用 [RAG Web Browser](https://apify.com/apify/rag-web-browser) Apify Actor。此 Actor 为 AI 和 LLM 应用程序提供网页浏览功能，类似于 ChatGPT 中的网页浏览功能。来自 [Apify Store](https://apify.com/store) 的任何 Actor 都可以以这种方式使用。

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

tool = ApifyActorsTool("apify/rag-web-browser")
```

## 调用

`ApifyActorsTool` 接受一个参数，即 `run_input`——一个作为运行输入传递给 Actor 的字典。运行输入模式文档可以在 Actor 详情页面的输入部分找到。参见 [RAG Web Browser 输入模式](https://apify.com/apify/rag-web-browser/input-schema)。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
tool.invoke({"run_input": {"query": "what is apify?", "maxResults": 2}})
```

## 链式调用

我们可以将创建的工具提供给一个[代理](https://python.langchain.com/docs/tutorials/agents/)。当被要求搜索信息时，代理将调用 Apify Actor，该 Actor 将搜索网络，然后检索搜索结果。

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

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain.messages import ToolMessage
from langchain_openai import ChatOpenAI
from langchain.agents import create_agent


model = ChatOpenAI(model="gpt-5-mini")
tools = [tool]
graph = create_agent(model, tools=tools)
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
inputs = {"messages": [("user", "search for what is Apify")]}
for s in graph.stream(inputs, stream_mode="values"):
    message = s["messages"][-1]
    # 跳过工具消息
    if isinstance(message, ToolMessage):
        continue
    message.pretty_print()
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
================================ Human Message =================================

search for what is Apify
================================== Ai Message ==================================
Tool Calls:
  apify_actor_apify_rag-web-browser (call_27mjHLzDzwa5ZaHWCMH510lm)
 Call ID: call_27mjHLzDzwa5ZaHWCMH510lm
  Args:
    run_input: {"run_input":{"query":"Apify","maxResults":3,"outputFormats":["markdown"]}}
================================== Ai Message ==================================

Apify 是一个用于网页抓取、浏览器自动化和数据提取的综合平台。它提供了广泛的工具和服务，旨在帮助开发者和企业高效且有效地从网站提取数据。以下是 Apify 的概述：

1. **生态系统和工具**：
   - Apify 提供了一个生态系统，开发者可以在其中构建、部署和发布称为 Actors 的数据提取和网页自动化工具。
   - 该平台支持各种用例，例如从社交媒体平台提取数据、执行基于浏览器的自动化任务等。

2. **产品**：
   - Apify 提供超过 10,000 个现成的抓取工具和代码模板。
   - 用户也可以构建自定义解决方案或聘请 Apify 的专业服务，以满足更定制化的数据提取需求。

3. **技术和集成**：
   - 该平台支持与流行工具和服务的集成，如 Zapier、GitHub、Google Sheets、Pinecone 等。
   - Apify 支持开源工具和技术，如 JavaScript、Python、Puppeteer、Playwright、Selenium 以及其自身的 Crawlee 库，用于网页爬取和浏览器自动化。

4. **社区和学习**：
   - Apify 在 Discord 上托管了一个社区，开发者可以在其中获得帮助并分享专业知识。
   - 它通过 Web Scraping Academy 提供教育资源，帮助用户精通数据抓取和自动化。

5. **企业解决方案**：
   - Apify 提供企业级的网页数据提取解决方案，具有高可靠性、99.95% 的正常运行时间，并符合 SOC2、GDPR 和 CCPA 标准。

有关更多信息，您可以访问 [Apify 的官方网站](https://apify.com/) 或他们的 [GitHub 页面](https://github.com/apify)，其中包含他们的代码仓库和有关其项目的更多详细信息。
```

## 其他 Actor 示例

Apify Store 包含数千个预构建的 Actor。以下是其他一些流行 Actor 的示例：

### Instagram Scraper

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

instagram_tool = ApifyActorsTool("apify/instagram-scraper")

# 抓取 Instagram 帖子
result = instagram_tool.invoke({
    "run_input": {
        "directUrls": ["https://www.instagram.com/humansofny/"],
        "resultsLimit": 10
    }
})
```

### Google Search Results Scraper

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
google_search_tool = ApifyActorsTool("apify/google-search-scraper")

# 抓取 Google 搜索结果
result = google_search_tool.invoke({
    "run_input": {
        "queries": "langchain python tutorial",
        "maxPagesPerQuery": 1
    }
})
```

浏览 [Apify Store](https://apify.com/store) 以发现更多适合您用例的 Actor。

## 何时使用 Apify

当您需要以下内容时，Apify 是理想的选择：

* **访问数千个预构建的 Actor**，适用于各种平台（社交媒体、电子商务、搜索引擎等）
* **自定义网页抓取和自动化工作流**，超越简单搜索
* **无基础设施抓取**（无服务器平台处理扩展和维护）
* **灵活的 Actor 生态系统** – 运行来自 Apify Store 的任何 Actor

***

## API 参考

有关如何使用此集成的更多信息，请参阅 [git 仓库](https://github.com/apify/langchain-apify) 或 [Apify 集成文档](https://docs.apify.com/platform/integrations/langgraph)。

***

## 使用 Apify MCP Server

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

要将 Apify MCP 服务器与 LangChain 一起使用：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import os
from langchain_mcp_adapters.client import MultiServerMCPClient
from langchain.agents import create_agent

client = MultiServerMCPClient({
    "apify": {
        "transport": "http",
        "url": "https://mcp.apify.com",
        "headers": {
            "Authorization": f"Bearer {os.environ['APIFY_TOKEN']}",
        },
    }
})

tools = await client.get_tools()
agent = create_agent("gpt-5-mini", tools)
```

有关更多信息，请参阅 [LangChain MCP 文档](/oss/python/langchain/mcp) 和 [Apify MCP 服务器](https://mcp.apify.com)。

***

<div className="source-links">
  <Callout icon="terminal-2">
    [将这些文档](/use-these-docs) 通过 MCP 连接到 Claude、VSCode 等，以获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/python/integrations/tools/apify_actors.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
