> ## 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.

# SitemapLoader 集成

> 使用 LangChain Python 集成 SitemapLoader 文档加载器。

`SitemapLoader` 继承自 `WebBaseLoader`，它从给定的 URL 加载站点地图，然后抓取并加载站点地图中的所有页面，将每个页面作为一个 Document 返回。

抓取过程是并发进行的。并发请求有合理的限制，默认每秒 2 个请求。如果您不担心成为良好网络公民，或者您控制被抓取的服务器，或者不关心负载，可以增加此限制。请注意，虽然这会加快抓取过程，但可能导致服务器屏蔽您。请谨慎操作！

## 概述

### 集成详情

| 类                                                                                                                    | 包                                                                                   |  本地 | 可序列化 | [JS 支持](https://js.langchain.com/docs/integrations/document_loaders/web_loaders/sitemap/) |
| :------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------- | :-: | :--: | :---------------------------------------------------------------------------------------: |
| [`SiteMapLoader`](https://reference.langchain.com/python/langchain-community/document_loaders/sitemap/SitemapLoader) | [`langchain-community`](https://reference.langchain.com/python/langchain-community) |  ✅  |   ❌  |                                             ✅                                             |

### 加载器特性

|        来源       | 文档惰性加载 | 原生异步支持 |
| :-------------: | :----: | :----: |
| `SiteMapLoader` |    ✅   |    ❌   |

## 设置

要使用 SiteMap 文档加载器，您需要安装 `langchain-community` 集成包。

### 凭证

运行此功能无需凭证。

要启用模型调用的自动追踪，请设置您的 [LangSmith](/langsmith/home) API 密钥：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
os.environ["LANGSMITH_TRACING"] = "true"
```

### 安装

安装 **langchain-community**。

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

### 修复 notebook 的 asyncio 错误

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

nest_asyncio.apply()
```

## 初始化

现在我们可以实例化模型对象并加载文档：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_community.document_loaders.sitemap import SitemapLoader
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
sitemap_loader = SitemapLoader(web_path="https://api.python.langchain.com/sitemap.xml")
```

## 加载

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
docs = sitemap_loader.load()
docs[0]
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
Fetching pages: 100%|##########| 28/28 [00:04<00:00,  6.83it/s]
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
Document(metadata={'source': 'https://api.python.langchain.com/en/stable/', 'loc': 'https://api.python.langchain.com/en/stable/', 'lastmod': '2024-05-15T00:29:42.163001+00:00', 'changefreq': 'weekly', 'priority': '1'}, page_content='\n\n\n\n\n\n\n\n\n\nLangChain Python API Reference Documentation.\n\n\nYou will be automatically redirected to the new location of this page.\n\n')
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
print(docs[0].metadata)
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{'source': 'https://api.python.langchain.com/en/stable/', 'loc': 'https://api.python.langchain.com/en/stable/', 'lastmod': '2024-05-15T00:29:42.163001+00:00', 'changefreq': 'weekly', 'priority': '1'}
```

您可以更改 `requests_per_second` 参数以增加最大并发请求数，并使用 `requests_kwargs` 在发送请求时传递关键字参数。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
sitemap_loader.requests_per_second = 2
# 可选：避免 `[SSL: CERTIFICATE_VERIFY_FAILED]` 问题
sitemap_loader.requests_kwargs = {"verify": False}
```

## 惰性加载

您也可以惰性加载页面，以最小化内存负载。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
page = []
for doc in sitemap_loader.lazy_load():
    page.append(doc)
    if len(page) >= 10:
        # 执行一些分页操作，例如：
        # index.upsert(page)

        page = []
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
Fetching pages: 100%|##########| 28/28 [00:01<00:00, 19.06it/s]
```

## 过滤站点地图 URL

站点地图可能是包含数千个 URL 的巨大文件。通常您不需要其中的每一个。您可以通过向 `filter_urls` 参数传递字符串列表或正则表达式模式来过滤 URL。只有匹配其中一个模式的 URL 才会被加载。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
loader = SitemapLoader(
    web_path="https://api.python.langchain.com/sitemap.xml",
    filter_urls=["https://api.python.langchain.com/en/latest"],
)
documents = loader.load()
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
documents[0]
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
Document(page_content='\n\n\n\n\n\n\n\n\n\nLangChain Python API Reference Documentation.\n\n\nYou will be automatically redirected to the new location of this page.\n\n', metadata={'source': 'https://api.python.langchain.com/en/latest/', 'loc': 'https://api.python.langchain.com/en/latest/', 'lastmod': '2024-02-12T05:26:10.971077+00:00', 'changefreq': 'daily', 'priority': '0.9'})
```

## 添加自定义抓取规则

`SitemapLoader` 使用 `beautifulsoup4` 进行抓取过程，默认情况下会抓取页面上的每个元素。`SitemapLoader` 构造函数接受一个自定义抓取函数。此功能有助于根据您的特定需求定制抓取过程；例如，您可能希望避免抓取页眉或导航元素。

以下示例展示了如何开发和使用自定义函数来避免导航和页眉元素。

安装 `beautifulsoup4` 库并定义自定义函数。

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

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


def remove_nav_and_header_elements(content: BeautifulSoup) -> str:
    # 在 BeautifulSoup 对象中查找所有 'nav' 和 'header' 元素
    nav_elements = content.find_all("nav")
    header_elements = content.find_all("header")

    # 从 BeautifulSoup 对象中移除每个 'nav' 和 'header' 元素
    for element in nav_elements + header_elements:
        element.decompose()

    return str(content.get_text())
```

将您的自定义函数添加到 `SitemapLoader` 对象。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
loader = SitemapLoader(
    "https://api.python.langchain.com/sitemap.xml",
    filter_urls=["https://api.python.langchain.com/en/latest/"],
    parsing_function=remove_nav_and_header_elements,
)
```

## 本地站点地图

站点地图加载器也可用于加载本地文件。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
sitemap_loader = SitemapLoader(web_path="example_data/sitemap.xml", is_local=True)

docs = sitemap_loader.load()
```

***

## API 参考

有关 `SiteMapLoader` 所有功能和配置的详细文档，请前往 [API 参考](https://reference.langchain.com/python/langchain-community/document_loaders/sitemap/SitemapLoader)

***

<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\sitemap.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>
