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 = '''

First paragraph

Second Paragraph

Main Paragraph

Fourth Paragraph

Fifth Pragaraph

''' 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:

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *