示例
from bs4 import BeautifulSoup
html_content = '''
<div id="content" data="你好">
<p>测试01</p>
<span>测试02</span>
</div>
<p>测试03</p>
'''.strip()
soup = BeautifulSoup(html_content, 'html.parser')
span_element = soup.select_one('span')
print(span_element)
print('''------ find_parent() ------''')
print(span_element.find_parent())
print('''------ find_parent('h1') ------''')
print(span_element.find_parent('h1'))
print('''------ find_parent('div') ------''')
print(span_element.find_parent('div'))
执行结果:
<span>测试02</span>
------ find_parent() ------
<div data="你好" id="content">
<p>测试01</p>
<span>测试02</span>
</div>
------ find_parent('h1') ------
None
------ find_parent('div') ------
<div data="你好" id="content">
<p>测试01</p>
<span>测试02</span>
</div>