Beautiful Soup - find() 方法



方法描述

Beautiful Soup 中的 find() 方法在該 PageElement 的子元素中查詢第一個與給定條件匹配的元素並返回它。

語法

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

引數

name - 標籤名稱過濾器。

attrs - 屬性值過濾器字典。

recursive - 如果為 True,則 find() 將執行遞迴搜尋。否則,只考慮直接子元素。

limit - 找到指定數量的匹配項後停止查詢。

kwargs - 屬性值過濾器字典。

返回值

find() 方法返回 Tag 物件或 NavigableString 物件

示例 1

讓我們使用以下 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>

以下 Python 程式碼查詢 id 為 nm 的元素

from bs4 import BeautifulSoup

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

obj = soup.find(id = 'nm')
print (obj)

輸出

<input id="nm" name="name" type="text"/>

示例 2

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

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

輸出

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

示例 3

如果 find() 找不到任何內容,則返回 None

obj = soup.find('dummy')
print (obj)

輸出

None
廣告