跳到主要內容
Open In ColabOpen on GitHub

Beautiful Soup

Beautiful Soup 是一個 Python 套件,用於剖析 HTML 和 XML 文件(包括具有格式錯誤的標記,即未封閉的標籤,因此以標籤湯命名)。它為剖析的頁面建立一個剖析樹,可用於從 HTML 中擷取資料,[3] 這對於網頁抓取非常有用。

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 '

此頁面是否對您有幫助?