共計 1063 個字符,預計需要花費 3 分鐘才能閱讀完成。
在 Python 中安裝 BeautifulSoup 庫,您可以使用 pip 工具
pip install beautifulsoup4
這將安裝 BeautifulSoup 4 的最新版本。安裝完成后,您可以在 Python 代碼中導入 BeautifulSoup 庫并使用它。
以下是一個簡單的示例,展示了如何使用 BeautifulSoup 解析 HTML 文檔:
from bs4 import BeautifulSoup
html_doc = """
<html><head<title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
soup = BeautifulSoup(html_doc, 'html.parser')
# 打印標題
print(soup.title.string)
# 打印所有鏈接
for link in soup.find_all('a'):
print(link.get('href'))
在這個示例中,我們首先導入 BeautifulSoup 庫,然后使用 BeautifulSoup 類解析 HTML 文檔。接下來,我們使用 soup.title.string 獲取標題,使用 soup.find_all('a') 查找所有的鏈接,并使用 link.get('href') 獲取鏈接的 href 屬性。
請注意,要使用 BeautifulSoup,您需要先安裝它。在安裝 BeautifulSoup 之前,請確保已經安裝了 Python 和 pip。
丸趣 TV 網 – 提供最優質的資源集合!
正文完