Open In App
Related Articles

Find the siblings of tags using BeautifulSoup

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Prerequisite: BeautifulSoup

BeautifulSoup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come in built-in with Python. To install this type the below command in the terminal. In this article, we will learn about siblings in HTML tags using BeautifulSoup.

Here we will discuss these four sibling properties:

  • previous_sibling is used to find the previous element of the given element
  • next_sibling is used to find the next element of the given element
  • previous_siblings is used to find all previous element of the given element
  • next_siblings is used to find all next element of the given element

Approach

  • Import module
  • Load or create HTML code
  • Parse HTML code
  • Print required sibling.

Example 1: To print next immediate sibling

Python3

# Import Module
from bs4 import BeautifulSoup
  
# HTML CODE
html_code = """<a><b>text1</b><c>text2</c></a>"""
  
# Parse HTML CODE
soup = BeautifulSoup(html_code, 'html.parser')
  
# next element
print(soup.b.next_sibling)

                    

Output:

<c>text2</c>

Example 2: To get previous immediate sibling

Python3

# Import Module
from bs4 import BeautifulSoup
  
# HTML CODE
html_code = """<a><b>text1</b><c>text2</c></a>"""
  
# Parse HTML CODE
soup = BeautifulSoup(html_code, 'html.parser')
  
# previous element
print(soup.c.previous_sibling)

                    

Output:

<b>text1</b>

Suppose we want to find all the next elements of a tag. For that, we just simply iterate through siblings and print the required tag.

Example 3: To get all siblings next to the tag

Python3

# Import Module
from bs4 import BeautifulSoup
  
# HTML CODE
html_code = """<a><b>text1</b><d>text3</d><c>text2</c></a>"""
  
# Parse HTML CODE
soup = BeautifulSoup(html_code, 'html.parser')
  
# next element
for element in soup.b.next_siblings:
    print(element)

                    

Output:

<d>text3</d>

<c>text2</c>

Example 4: To get all previous siblings

Python3

# Import Module
from bs4 import BeautifulSoup
  
# HTML CODE
html_code = """<a><b>text1</b><d>text3</d><c>text2</c></a>"""
  
# Parse HTML CODE
soup = BeautifulSoup(html_code, 'html.parser')
  
# previous element
for element in soup.c.previous_siblings:
    print(element)

                    

Output:

<d>text3</d>

<b>text1</b>



Last Updated : 03 Mar, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads