注意,获取的结果和当前元素不一定是同级关系。
示例
from bs4 import BeautifulSoup
html_content = '''
<div id="content" data="你好">
<p>测试01</p>
</div>
<span>测试02</span>
<p>测试03</p>
'''.strip()
soup = BeautifulSoup(html_content, 'html.parser')
span_element = soup.select_one('span')
print(span_element)
print('''------ find_previous('h1') ------''')
print(span_element.find_previous('h1'))
print('''------ find_previous('div') ------''')
print(span_element.find_previous('div'))
print('''------ find_previous('p') ------''')
print(span_element.find_previous('p'))
print('''------ find_previous() ------''')
print(span_element.find_previous())
print('''------ find_next('div') ------''')
print(span_element.find_next('div'))
print('''------ find_next('p') ------''')
print(span_element.find_next('p'))
print('''------ find_next() ------''')
print(span_element.find_next())
执行结果:
<span>测试02</span>
------ find_previous('h1') ------
None
------ find_previous('div') ------
<div data="你好" id="content">
<p>测试01</p>
</div>
------ find_previous('p') ------
<p>测试01</p>
------ find_previous() ------
<p>测试01</p>
------ find_next('div') ------
None
------ find_next('p') ------
<p>测试03</p>
------ find_next() ------
<p>测试03</p>