Beautiful Soup 简明教程
Beautiful Soup - find_parent() Method
Method Description
BeautifulSoup 包中的 find_parent() 方法找到与给定条件匹配的此 PageElement 的最近父级。
The find_parent() method in BeautifulSoup package finds the closest parent of this PageElement that matches the given criteria.
Parameters
-
name − A filter on tag name.
-
attrs − A dictionary of filters on attribute values.
-
kwargs − A dictionary of filters on attribute values.
Return Type
find_parent() 方法返回标记对象或 NavigableString 对象。
The find_parent() method returns Tag object or a NavigableString object.
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>
在以下示例中,我们找到包含字符串“HR”的标记的名称。
In the following example, we find the name of the tag that is parent to the string 'HR'.
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
obj=soup.find(string='HR')
print (obj.find_parent().name)
Example 2
<body> 标记始终包含在顶级 <html> 标记中。在以下示例中,我们使用 find_parent() 方法来确认这一事实 -
The <body> tag is always enclosed within the top level <html> tag. In the following example, we confirm this fact with find_parent() method −
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
obj=soup.find('body')
print (obj.find_parent().name)