Skip to main content
Open In Colab在 GitHub 上打开

美汤

Beautiful Soup 是一个用于解析的 Python 包 HTML 和 XML 文档(包括格式错误的标记,即非封闭标签,因此以标签 soup 命名)。 它为解析的页面创建一个解析树,可用于从 HTML 中提取数据,[3] 对于网络抓取很有用。

Beautiful Soup提供对 HTML 内容的精细控制,支持特定的标签提取、删除和内容清理。

它适用于您希望根据需要提取特定信息并清理 HTML 内容的情况。

例如,我们可以抓取其中的文本内容<p>, <li>, <div>, and <a>标记中:

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

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

  • <div>:division 标签。它是一个块级元素,用于对其他内联或块级元素进行分组。

  • <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 '