Beautiful Soup - find 與 find_all 方法



Beautiful Soup 庫包含 find() 和 find_all() 方法。這兩種方法是解析 HTML 或 XML 文件時最常用的方法之一。您經常需要從特定的文件樹中找到具有特定標籤型別、特定屬性或特定 CSS 樣式等的 PageElement。這些條件作為引數傳遞給 find() 和 find_all() 方法。兩者之間的主要區別在於,find() 定位滿足條件的第一個子元素,而 find_all() 方法搜尋滿足條件的所有子元素。

find() 方法的語法如下:

語法

find(name, attrs, recursive, string, **kwargs)

name 引數指定對標籤名稱的過濾。使用 attrs,可以設定對標籤屬性值的過濾。如果 recursive 引數為 True,則強制進行遞迴搜尋。您可以將變數 kwargs 作為屬性值過濾器的字典傳遞。

soup.find(id = 'nm')
soup.find(attrs={"name":'marks'})

find_all() 方法採用與 find() 方法相同的所有引數,此外還有一個 limit 引數。它是一個整數,將搜尋限制為給定過濾條件的指定出現次數。如果沒有設定,find_all() 將在所述 PageElement 下的所有子元素中搜索條件。

soup.find_all('input')
lst=soup.find_all('li', limit =2)

如果 find_all() 方法的 limit 引數設定為 1,則它實際上充當 find() 方法。

兩種方法的返回型別不同。find() 方法返回首先找到的 Tag 物件或 NavigableString 物件。find_all() 方法返回一個 ResultSet,其中包含滿足過濾條件的所有 PageElement。

以下示例演示了 find 和 find_all 方法的區別。

示例

from bs4 import BeautifulSoup

markup =open("index.html")

soup = BeautifulSoup(markup, 'html.parser')
ret1 = soup.find('input')
ret2 = soup.find_all ('input')
print (ret1, 'Return type of find:', type(ret1))
print (ret2)
print ('Return tyoe find_all:', type(ret2))

#set limit =1
ret3 = soup.find_all ('input', limit=1)
print ('find:', ret1)
print ('find_all:', ret3)

輸出

<input id="nm" name="name" type="text"/> Return type of find: <class 'bs4.element.Tag'>
[<input id="nm" name="name" type="text"/>, <input id="age" name="age" type="text"/>, <input id="marks" name="marks" type="text"/>]
Return tyoe find_all: <class 'bs4.element.ResultSet'>
find: <input id="nm" name="name" type="text"/>
find_all: [<input id="nm" name="name" type="text"/>]
廣告