Skip to main content
Open In ColabOpen on GitHub

如何加载HTML

超文本标记语言或 HTML 是用于在网页浏览器中显示文档的标准标记语言。

这介绍了如何将 HTML 个文档加载到 LangChain Document 对象中,以便在后续步骤中使用。

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

加载包含非结构化内容的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

%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'})]