Open In App

Find the siblings of tags using BeautifulSoup

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:

Approach



Example 1: To print next immediate sibling




# 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




# 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




# 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




# 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>


Article Tags :