跳到主要内容
Open In ColabOpen on GitHub

如何加载HTML

超文本标记语言或 HTML 是为在网页浏览器中显示文档而设计的标准标记语言。

本文介绍如何将 HTML 文档加载到 LangChain Document 对象中,以便我们后续使用。

解析 HTML 文件通常需要专门的工具。这里我们演示通过 UnstructuredBeautifulSoup4 进行解析,它们可以通过 pip 安装。前往集成页面可以找到与其他服务的集成,例如 Azure AI 文档智能FireCrawl

使用 Unstructured 加载 HTML

%pip install unstructured
from langchain_community.document_loaders import UnstructuredHTMLLoader

file_path = "../../docs/integrations/document_loaders/example_data/fake-content.html"

loader = UnstructuredHTMLLoader(file_path)
data = loader.load()

print(data)
[Document(page_content='My First Heading\n\nMy first paragraph.', metadata={'source': '../../docs/integrations/document_loaders/example_data/fake-content.html'})]

使用 BeautifulSoup4 加载 HTML

我们也可以使用 BeautifulSoup4 通过 BSHTMLLoader 加载 HTML 文档。这将从 HTML 中提取文本到 page_content,并将页面标题作为 title 提取到 metadata 中。

%pip install bs4
from langchain_community.document_loaders import BSHTMLLoader

loader = BSHTMLLoader(file_path)
data = loader.load()

print(data)
API 参考:BSHTMLLoader
[Document(page_content='\nTest Title\n\n\nMy First Heading\nMy first paragraph.\n\n\n', metadata={'source': '../../docs/integrations/document_loaders/example_data/fake-content.html', 'title': 'Test Title'})]