Beautiful Soup 简明教程

Beautiful Soup - find_parents() Method

Method Description

BeautifulSoup 包中的 find_parent() 方法可以找到满足给定条件的该元素的所有父元素。

The find_parent() method in BeautifulSoup package finds all parents of this Element that matches the given criteria.

Syntax

find_parents( name, attrs, limit, **kwargs)

Parameters

name − 对标记名称的筛选。

name − A filter on tag name.

attrs − 对属性值进行筛选的字典。

attrs − A dictionary of filters on attribute values.

limit − 在找到指定数量的出现次数后停止寻找。

limit − Stop looking after specified number of occurrences have been found.

kwargs − 对属性值进行筛选的字典。

kwargs − A dictionary of filters on attribute values.

Return Type

find_parents() 方法返回一个 ResultSet,其中包含所有父元素,并且它们的顺序相反。

The find_parents() method returns a ResultSet consisting of all the parent elements in a reverse order.

Example 1

我们将在本示例中使用以下 HTML 脚本:

We shall use following HTML script in this example −

<html>
   <body>
   <h2>Departmentwise Employees</h2>
   <ul id="dept">
   <li>Accounts</li>
      <ul id='acc'>
      <li>Anand</li>
      <li>Mahesh</li>
      </ul>
   <li>HR</li>
      <ol id="HR">
      <li>Rani</li>
      <li>Ankita</li>
      </ol>
   </ul>
   </body>
</html>

Output

ul
body
html
[document]

请注意,BeautifulSoup 对象的 name 属性总是返回 [document]。

Note that the name property of BeautifulSoup object always returns [document].

Example 2

在此示例中, limit 参数传递给 find_parents() 方法,以将父对象搜索限制在向上两级以内。

In this example, the limit argument is passed to find_parents() method to restrict the parent search to two levels up.

from bs4 import BeautifulSoup

soup = BeautifulSoup(html, 'html.parser')
obj=soup.find('li')
parents=obj.find_parents(limit=2)
for parent in parents:
   print (parent.name)

Output

ul
body