> 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/ai-workflows/cn/langchain.md).

# LangChain

将 LangChain 框架与 Oxylabs 网页爬虫API 搭配使用，以提取网页数据并将其输入 LLM 工作流——在一个流程中收集、处理、分析。

该 **LangChain** 与……的集成 [**网页爬虫API**](https://oxylabs.io/products/scraper-api/web) 可让你通过同一工作流中的 LLM（大语言模型）收集和处理网页数据。

## 概述

**LangChain** 是一个用于构建将 LLM 与工具、API 和网页数据结合使用的应用程序框架。它支持 Python 和 JavaScript。将其与 [**网页爬虫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()
```

## 集成方法

将网页爬虫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()

# Initialize your preferred LLM model
llm = init_chat_model(
    "gpt-4o-mini",
    model_provider="openai",
    api_key=os.getenv("OPENAI_API_KEY")
)

# Initialize the Google search tool
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/) 适用于各种热门网站。以下是一些可用来源的示例：

| 网站      | 来源参数             | 必需参数                   |
| ------- | ---------------- | ---------------------- |
| 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` 函数中的负载：

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

## 高级配置

### 处理动态内容

网页爬虫API 可以处理 [**JavaScript 渲染**](broken://pages/b13f2324d7ab32cbd7bfd790d22dd311dc9f266f) 只需添加 `render` 参数：

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

### 设置用户代理类型

您可以指定不同的 [**用户代理**](broken://pages/7e1c624d5094b4ed4920d8739428d245a60ad10a) 以模拟不同设备：

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

### 使用目标网站专用参数

许多 [**目标网站专用爬虫**](https://developers.oxylabs.io/api-targets/) 支持附加参数：

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

## 错误处理

为生产应用实现正确的错误处理：

```python
try:
    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 error occurred: {http_err}")
except requests.exceptions.ConnectionError as conn_err:
    print(f"Connection error occurred: {conn_err}")
except requests.exceptions.Timeout as timeout_err:
    print(f"Timeout error occurred: {timeout_err}")
except requests.exceptions.RequestException as req_err:
    print(f"An error occurred: {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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://developers.oxylabs.io/ai-workflows/cn/langchain.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
