Beautiful Soup - 透過屬性查詢元素



find() 和 find_all() 方法都用於根據傳遞給這些方法的引數查詢文件中一個或所有標籤。您可以將 attrs 引數傳遞給這些函式。attrs 的值必須是一個字典,其中包含一個或多個標籤屬性及其值。

為了檢查這些方法的行為,我們將使用以下HTML文件 (index.html)

<html>
   <head>
      <title>TutorialsPoint</title>
   </head>
   <body>
      <form>
         <input type = 'text' id = 'nm' name = 'name'>
         <input type = 'text' id = 'age' name = 'age'>
         <input type = 'text' id = 'marks' name = 'marks'>
      </form>
   </body>
</html>

使用 find_all()

以下程式返回所有具有 input type="text" 屬性的標籤列表。

示例

from bs4 import BeautifulSoup

fp = open("index.html")
soup = BeautifulSoup(fp, 'html.parser')

obj = soup.find_all(attrs={"type":'text'})
print (obj)

輸出

[<input id="nm" name="name" type="text"/>, <input id="age" name="age" type="text"/>, <input id="marks" name="marks" type="text"/>]

使用 find()

find() 方法返回已解析文件中第一個具有給定屬性的標籤。

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

使用 select()

select() 方法可以透過傳遞要比較的屬性來呼叫。屬性必須放在列表物件中。它返回所有具有給定屬性的標籤列表。

在以下程式碼中,select() 方法返回所有具有 type 屬性的標籤。

示例

from bs4 import BeautifulSoup

fp = open("index.html")
soup = BeautifulSoup(fp, 'html.parser')

obj = soup.select("[type]")
print (obj)

輸出

[<input id="nm" name="name" type="text"/>, <input id="age" name="age" type="text"/>, <input id="marks" name="marks" type="text"/>]

使用 select_one()

select_one() 方法與此類似,只是它返回滿足給定過濾器的第一個標籤。

obj = soup.select_one("[name='marks']")

輸出

<input id="marks" name="marks" type="text"/>
廣告