Skip to main content
Open In ColabOpen on GitHub

Beautiful Soup

Beautiful Soup 是一个用于解析 HTML 和 XML 文档(包括非良构的标记,例如未关闭的标签,因此得名 tag soup)的 Python 包。它为解析后的页面创建一个解析树,可用于从 HTML 中提取数据,非常适合网络抓取。

Beautiful Soup 在 HTML 内容方面提供了精细的控制,能够实现特定标签的提取、移除和内容清理。

它适用于你想提取特定信息并根据需求清理 HTML 内容的场景。

例如,我们可以从 HTML 内容中抓取 <p>, <li>, <div>, 和 <a> 标签内的文本内容:

  • <p>: 段落标签。它在 HTML 中定义一个段落,并用于将相关的句子和/或短语组合在一起。

  • <li>: 列表项标签。它在有序列表 (<ol>) 和无序列表 (<ul>) 中使用,用于定义列表中的单个项。

  • <div>: 区域标签。它是一个块级元素,用于组合其他内联或块级元素。

  • <a>: 锚点标签。它用于定义超链接。

from langchain_community.document_loaders import AsyncChromiumLoader
from langchain_community.document_transformers import BeautifulSoupTransformer

# Load HTML
loader = AsyncChromiumLoader(["https://www.wsj.com"])
html = loader.load()
# Transform
bs_transformer = BeautifulSoupTransformer()
docs_transformed = bs_transformer.transform_documents(
html, tags_to_extract=["p", "li", "div", "a"]
)
docs_transformed[0].page_content[0:500]
'Conservative legal activists are challenging Amazon, Comcast and others using many of the same tools that helped kill affirmative-action programs in colleges.1,2099 min read U.S. stock indexes fell and government-bond prices climbed, after Moody’s lowered credit ratings for 10 smaller U.S. banks and said it was reviewing ratings for six larger ones. The Dow industrials dropped more than 150 points.3 min read Penn Entertainment’s Barstool Sportsbook app will be rebranded as ESPN Bet this fall as '