如何使用 BeautifulSoup 搜尋解析樹?
查詢標籤和 HTML 樹的內容表示使用 BeautifulSoup 搜尋解析樹。還有其他方法可以實現這一點,但 find() 和 find_all() 方法是搜尋解析樹最常用的方法。我們可以藉助這些技術使用 BeautifulSoup 解析 HTML 樹。應用 Beautiful Soup 的一個好處是,即使我們從另一種語言轉向,初學者也很容易學習。它提供了出色、詳盡的文件,使我們能夠快速掌握內容。
語法
以下語法在示例中使用:
BeautifulSoup()
Beautiful Soup 是 Python 程式中一個內建方法,用於從 HTML 和 XML 檔案中提取資料。它使我們能夠搜尋、導航和更新資料搜尋的結構以及導航和更新這些檔案中的資料結構。
find()
這是一個 Python 中的內建函式,可用於確定給定文字中子字串第一次出現的索引。
find_all()
find_all() 是 Python 中一個內建的 BeautifulSoup 庫方法,它會顯示滿足指定條件的所有標籤的所有出現。它返回所有匹配的標籤列表。
安裝要求:
pip install beautifulsoup4
這是必要的安裝命令,可用於執行基於 BeautifulSoup 的程式。
方法 1:搜尋特定標籤
此程式使用兩個內建方法 - BeautifulSoup(),它接受兩個引數,即 html_content,透過在其中使用一些標籤將值設定為 HTML 程式碼,以及 html.parser,它是一個用於處理結構化標記的工具。它定義了 HTMLParser 類,用於解析 HTML 檔案。它有助於網路爬蟲或網路抓取。
示例
from bs4 import BeautifulSoup # Storing of HTML Tags html_content = ''' <html> <body> <h1>Title</h1> <p>This is paragraph</p> </body> </html> ''' # Create the BeautifulSoup object soup = BeautifulSoup(html_content, 'html.parser') # Search for the <h1> tag p_tag = soup.find('p') if p_tag: print("Found <p> tag:", p_tag.text) else: print("The <p> tag not found")
輸出
Found <h1> tag: This is paragraph
方法 2:搜尋多個標籤
該程式使用兩個方法 BeautifulSoup() 和 find_all(),它們將計算以查詢多個標籤,如 p 標籤或任何其他標籤。find_all() 方法返回多個標籤的列表。
示例
from bs4 import BeautifulSoup # Storing of HTML Tags html_content = ''' <html> <body> <h1>Title</h1> <p>Paragraph 1</p> <p>Paragraph 2</p> <h3>Hello World</h3> <h3>Inner World</h3> </body> </html> ''' # Create a BeautifulSoup object soup = BeautifulSoup(html_content, 'html.parser') # Search for all <p> tags h3_tags = soup.find_all('h3') if h3_tags: print("Found", len(h3_tags), "<h3> tags:") for h3 in h3_tags: print(h3.text) else: print("Could not find any <h3> tags")
輸出
Found 2 <h3> tags: Hello World Inner World
方法 3:搜尋具有特定屬性的標籤
該程式使用兩個方法 BeautifulSoup() 和 find() [它接受兩個引數 - tag_name 和 attrs={‘id’: ‘id_name’}],它們將查詢具有特定屬性的標籤。
示例
from bs4 import BeautifulSoup # Storing of HTML tags html_content = ''' <html> <body> <h1 class="title">Title</h1> <p id="para1">Paragraph 1</p> <p id="para2">Paragraph 2</p> </body> </html> ''' # Create a BeautifulSoup object soup = BeautifulSoup(html_content, 'html.parser') # Search for the <p> tag with id="paragraph2" p_tag = soup.find('p', attrs={'id': 'para2'}) if p_tag: print("Found <p> tag with id='para2':", p_tag.text) else: print("Could not find <p> tag with id='para2'")
輸出
Found <p> tag with id='para2': Paragraph 2
結論
我們討論了三種不同的方法來解決基於使用 BeautifulSoup 搜尋解析樹的問題陳述。建立 BeautifulSoup 物件後,我們可以使用其方法來導航和從 HTML 內容中提取資料。它通常用作其他應用程式或指令碼中用於從 HTML 和 XML 檔案中進行網路抓取和資料提取的工具。