Beautiful Soup - find_previous_sibling() Method



Method Description

The find_previous_sibling() method in Beautiful Soup returns the closest sibling to this PageElement that matches the given criteria and appears earlier in the document.

Syntax

find_previous_sibling(name, attrs, string, **kwargs)

Parameters

  • name − A filter on tag name.

  • attrs − A dictionary of filters on attribute values.

  • string − A filter for a NavigableString with specific text.

  • kwargs − A dictionary of filters on attribute values.

Return Value

The find_previous_sibling() method returns a PageElement that could be a Tag or a NavigableString.

Example 1

From the HTML string used in the following example, we find out the previous sibling of <i> tag, having the tag name as 'u'

from bs4 import BeautifulSoup

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

Output

<u>Excellent</u>

Example 2

The web page (index.html) has a HTML form with three input elements. We locate one with id attribute as marks and then find its previous sibling that had id set to nm.

from bs4 import BeautifulSoup

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

tag = soup.find('input', {'id':'marks'})
sib = tag.find_previous_sibling(id='nm')
print (sib)

Output

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

Example 3

In the code below, the HTML string has two <p> elements and a string inside the outer <p> tag. We use find_previous_string() method to search for the NavigableString object sibling of <p>Tutorial</p> tag.

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

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

tag = soup.find('p', string='Tutorial')
ptag = tag.find_previous_sibling(string='Excellent')
print (ptag, type(ptag))

Output

Excellent <class 'bs4.element.NavigableString'>
Advertisements