一、方法描述
在 BeautifulSoup 库中,find_parent() 方法用于查找最接近的父元素,该元素与给定的条件相匹配。
二、语法
find_parent(name, attrs, **kwargs)
三、参数
四、返回类型
find_parent() 方法返回一个 Tag 对象或 NavigableString 对象。
五、示例
示例 1
我们将使用以下 HTML 脚本来进行这个例子:
<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' 的标签的父标签名称。
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
obj = soup.find(string='HR')
print(obj.find_parent().name)
输出:
li
示例 2
<body> 标签总是被顶层的 <html> 标签所包围。在下面的例子中,我们用 find_parent() 方法确认了这一事实。
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
obj = soup.find('body')
print(obj.find_parent().name)
输出:
html