How to find sibling HTML nodes using BeautifulSoup and Python?

BeautifulSoup allows us to find sibling elements using 4 main functions:

find_previous_sibling to find the single previous sibling
find_next_sibling to find the single next sibling
find_all_next to find all the next siblings
find_all_previous to find all previous siblings

​​​​​​​You can use the code below to find the previous sibling, next sibling, all next siblings and all previous siblings of the Main Paragraph element:

from bs4 import BeautifulSoup

html_content = '''
<p>First paragraph</p>
<p>Second Paragraph</p>
<p id="main">Main Paragraph</p>
<p>Fourth Paragraph</p>
<p>Fifth Pragaraph</p>
'''
soup = BeautifulSoup(html_content, 'html.parser')

main_element = soup.find("p", attrs={"id": "main"})

# Find the previous sibling:
print(main_element.find_previous_sibling())

# Find the next sibling:
print(main_element.find_next_sibling())

# Find all next siblings:
print(main_element.find_all_next())

# Find all previous siblings:
print(main_element.find_all_previous())

Related BeautifulSoup web scraping questions: