> 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/integrations/cn/web-scraper-api-integrations/langchain.md).

# LangChain

将 LangChain 框架与 Oxylabs 网页爬虫API 结合使用，提取网页数据并将其输入 LLM 工作流——在一个流水线中完成收集、处理和分析。

该 **LangChain** 与以下内容集成 [**Oxylabs 网页爬虫API**](https://oxylabs.io/products/scraper-api/web) 使你能够在同一工作流中通过 LLM（大语言模型）收集和处理网页数据。

## 概述

**LangChain** 是一个用于构建将 LLM 与工具、API 和网页数据结合使用的应用的框架。它支持 Python 和 JavaScript。与以下内容一起使用： [**Oxylabs 网页爬虫API** ](http://developers.oxylabs.io/scraper-apis/web-scraper-api?_gl=1*1ljhay3*_gcl_aw*R0NMLjE3NDYxODM0ODcuQ2owS0NRancydEhBQmhDaUFSSXNBTlp6RFdvSXlSNVg3blQtd0ZEakxHOUlvdUhyQmtoRTRCeUNwc054dFJVMmh0Z3dZTTR3Nm90SjVKOGFBbHhhRUFMd193Y0I.*_gcl_au*MjU4NDEzMTkwLjE3NDExNzU2MzI.)结合使用以：

* 抓取结构化数据，无需处理 CAPTCHA、IP 封锁或 JS 渲染
* 在同一管道中使用 LLM 处理结果
* 构建从提取到 AI 驱动输出的端到端工作流

## 入门

**创建你的 API 用户凭证**: 注册免费试用或在以下位置购买产品 [**Oxylabs 控制面板**](https://dashboard.oxylabs.io/en/registration) 以创建您的 API 用户凭据（`USERNAME` 并 `PASSWORD`).

{% hint style="warning" %}
如果你的账户需要多个 API 用户，请联系我们的 [**客户支持**](mailto:support@oxylabs.io) 或通过我们的 24/7 在线聊天支持发送消息。
{% endhint %}

本指南将使用 Python 编程语言。使用 pip 安装所需的库：

```bash
pip install -qU langchain-oxylabs langchain-openai langgraph requests python-dotenv
```

## 环境设置

在您的项目目录中创建一个 `.env` 在你的项目目录中创建一个包含 Oxylabs API 用户和 OpenAI 凭证的文件：

```
OXYLABS_USERNAME=your-username
OXYLABS_PASSWORD=your-password
OPENAI_API_KEY=your-openai-key
```

在您的 Python 脚本中加载这些环境变量：

```python
import os
from dotenv import load_dotenv

load_dotenv()
```

## 集成方法

将 Oxylabs 网页爬虫API 与 LangChain 集成主要有两种方式：

### 使用 langchain-oxylabs 包

对于 Google 搜索查询，请使用专用的 [`langchain-oxylabs`](https://python.langchain.com/docs/integrations/tools/oxylabs/) 包，它提供开箱即用的集成：

```python
import os
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
from langgraph.prebuilt import create_react_agent
from langchain_oxylabs import OxylabsSearchAPIWrapper, OxylabsSearchRun

load_dotenv()

# 初始化你偏好的 LLM 模型
llm = init_chat_model(
    "gpt-4o-mini",
    model_provider="openai",
    api_key=os.getenv("OPENAI_API_KEY")
)

# 初始化 Google 搜索工具
search = OxylabsSearchRun(
    wrapper=OxylabsSearchAPIWrapper(
        oxylabs_username=os.getenv("OXYLABS_USERNAME"),
        oxylabs_password=os.getenv("OXYLABS_PASSWORD")
    )
)

# 创建一个使用 Google 搜索工具的代理
agent = create_react_agent(llm, [search])

# 示例用法
user_input = "玛雅文明是什么时候以及为什么崩溃的？"
response = agent.invoke({"messages": user_input})
print(response["messages"][-1].content)
```

### 使用网页爬虫API

对于访问除 Google 搜索之外的其他网站，你可以直接向网页爬虫API发送请求：

```python
import os
import requests
from dotenv import load_dotenv
from langchain_openai import OpenAI
from langchain_core.prompts import PromptTemplate

load_dotenv()

def scrape_website(url):
    """使用 Oxylabs 网页爬虫API 抓取网站"""
    payload = {
        "source": "universal",
        "url": url,
        "parse": True
    }
    response = requests.post(
        "https://realtime.oxylabs.io/v1/queries",
        auth=(os.getenv("OXYLABS_USERNAME"), os.getenv("OXYLABS_PASSWORD")),
        json=payload
    )
    
    if response.status_code == 200:
        data = response.json()
        content = data["results"][0]["content"]
        return str(content)
    else:
        print(f"抓取网站失败：{response.text}")
        return None

def process_content(content):
    """使用 LangChain 处理抓取的内容"""
    if not content:
        print("没有可处理的内容。")
        return None
        
    prompt = PromptTemplate.from_template(
        "分析以下网站内容并总结要点：{content}"
    )
    chain = prompt | OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
    result = chain.invoke({"content": content})
    return result

def main(url):
    print("正在抓取网站...")
    scraped_content = scrape_website(url)
    if scraped_content:
        print("正在使用 LangChain 处理抓取的内容...")
        analysis = process_content(scraped_content)
        print("\n处理后的分析：\n", analysis)
    else:
        print("未抓取到内容。")

if __name__ == "__main__":
    url = "https://sandbox.oxylabs.io/products/1"
    main(url)
```

## 面向特定目标的抓取器

Oxylabs 提供 [**专用抓取器**](https://developers.oxylabs.io/api-targets/cn/) 用于各种常见网站。以下是一些可用源的示例：

| 网站      | 源参数              | 所需参数                   |
| ------- | ---------------- | ---------------------- |
| Google  | `google_search`  | `query`                |
| Amazon  | `amazon_search`  | `query`, `domain` （可选） |
| Walmart | `walmart_search` | `query`                |
| Target  | `target_search`  | `query`                |
| Kroger  | `kroger_search`  | `query`, `store_id`    |
| Staples | `staples_search` | `query`                |

要使用特定抓取器，请修改 `scrape_website` 函数中的 payload：

```python
# Amazon 搜索示例
payload = {
    "source": "amazon_search",
    "query": "smartphone",
    "domain": "com",
    "parse": True
}
```

## 高级配置

### 处理动态内容

网页爬虫API 可以处理 [**JavaScript 渲染**](/products/cn/web-scraper-api/features/js-rendering-and-browser-control.md) 通过添加 `render` 参数：

```python
payload = {
    "source": "universal",
    "url": url,
    "parse": True,
    "render": "html"
}
```

### 设置用户代理类型

你可以指定不同的 [**用户代理**](/products/cn/web-scraper-api/features/http-context-and-job-management/user-agent-type.md) 来模拟不同设备：

```python
payload = {
    "source": "universal",
    "url": url,
    "parse": True,
    "render": "html",
    "user_agent_type": "mobile"
}
```

### 使用目标特定参数

许多 [**面向特定目标的抓取器**](https://developers.oxylabs.io/api-targets/cn/) 支持额外参数：

```python
# Kroger 位置参数示例
payload = {
    "source": "kroger_search",
    "query": "organic milk",
    "store_id": "01100002",
    "fulfillment_type": "pickup"
}
```

## 错误处理

为生产环境应用实现适当的错误处理：

```python
尝试：
    response = requests.post(
        "https://realtime.oxylabs.io/v1/queries",
        auth=(os.getenv("OXYLABS_USERNAME"), os.getenv("OXYLABS_PASSWORD")),
        json=payload,
        timeout=60
    )
    response.raise_for_status()
    # 处理响应
except requests.exceptions.HTTPError as http_err:
    print(f"发生 HTTP 错误：{http_err}")
except requests.exceptions.ConnectionError as conn_err:
    print(f"发生连接错误：{conn_err}")
except requests.exceptions.Timeout as timeout_err:
    print(f"发生超时错误：{timeout_err}")
except requests.exceptions.RequestException as req_err:
    print(f"发生错误：{req_err}")
```


---

# 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, and the optional `goal` query parameter:

```
GET https://developers.oxylabs.io/integrations/cn/web-scraper-api-integrations/langchain.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
