Beautiful Soup - previous_sibling Property



Method Description

The HTML tags appearing at the same indentation level are called siblings. The previous_sibling property of the PageElement returns a previous tag (a tag appearing before the current tag) at the same level, or under the same parent. This property encapsulates the find_previous_sibling() method.

Syntax

element.previous_sibling

Return type

The previous_sibling property returns a PageElement, a Tag or a NavigableString object.

Example 1

In the following code, the HTML string consists of two adjacent tags inside a <p> tag. It shows the sibling tag for <b> tag appearing before it.

from bs4 import BeautifulSoup

fp = open("index.html")
soup = BeautifulSoup("<p><b>Hello</b><i>Python</i></p>", 'html.parser')
tag = soup.i
sibling = tag.previous_sibling
print (sibling)

Output

<b>Hello</b>

Example 2

We are using the index.html file for parsing. The page contains a HTML form with three input elements. Which element is a previous sibling of input element with its id attribute as age? The following code shows it −

from bs4 import BeautifulSoup

fp = open("index.html")
soup = BeautifulSoup(fp, 'html.parser')

tag = soup.find('input', {'id':'age'})
sib = tag.previous_sibling.previous_sibling
print (sib)

Output

<input id="nm" name="name" type="text"/>

Example 3

First we find the <p> tag containing the string 'Tutorial' and then fins a tag previous to it.

html = '''
<p>Excellent</p><p>Python</p><p>Tutorial</p>
'''
from bs4 import BeautifulSoup

soup = BeautifulSoup(html, 'html.parser')

tag = soup.find('p', string='Tutorial')
print (tag.previous_sibling)

Output

<p>Python</p>
Advertisements