方法:find_previous_sibling 、find_next_sibling。
示例
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_sibling('h1') ------''')
print(span_element.find_previous_sibling('h1'))
print('''------ find_previous_sibling('div') ------''')
print(span_element.find_previous_sibling('div'))
print('''------ find_previous_sibling('p') ------''')
print(span_element.find_previous_sibling('p'))
print('''------ find_previous_sibling() ------''')
print(span_element.find_previous_sibling())
print('''------ find_next_sibling('div') ------''')
print(span_element.find_next_sibling('div'))
print('''------ find_next_sibling('p') ------''')
print(span_element.find_next_sibling('p'))
print('''------ find_next_sibling() ------''')
print(span_element.find_next_sibling())
执行结果:
<span>测试02</span>
------ find_previous_sibling('h1') ------
None
------ find_previous_sibling('div') ------
<div data="你好" id="content">
<p>测试01</p>
</div>
------ find_previous_sibling('p') ------
None
------ find_previous_sibling() ------
<div data="你好" id="content">
<p>测试01</p>
</div>
------ find_next_sibling('div') ------
None
------ find_next_sibling('p') ------
<p>测试03</p>
------ find_next_sibling() ------
<p>测试03</p>