Beautiful Soup - previous_element Property



Method Description

In Beautiful Soup library, the previous_element property returns the Tag or NavigableString that appears immediately prior to the current PageElement, even if it is out of the parent tree. There is also a previous property which has similar behaviour

Syntax

Element.previous_element

Return value

The previous_element and previous properties return a tag or a NavigableString appearing immediately before the current tag.

Example 1

In the document tree parsed from the given HTML string, we find the previous_element of the <p id='id1'> tag

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

soup = BeautifulSoup(html, 'lxml')
tag = soup.find('p', id='id1')
print (tag)
pre = tag.previous_element
print ("Previous:",pre)

pre = tag.previous_element.previous_element
print ("Previous:",pre)

Output

<p id="id1">Tutorial</p>
Previous: Python
Previous: <p>Python</p>

The output is a little strange as the previous element for shown to be 'Python, that is because the inner string is registered as the previous element. To obtain the desired result (<p>Python</p>) as the previous element, fetch the previous_element property of the inner NavigableString object.

Example 2

The BeautifulSoup PageElements also supports previous property which is analogous to previous_element property

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

soup = BeautifulSoup(html, 'lxml')
tag = soup.find('p', id='id1')
print (tag)
pre = tag.previous
print ("Previous:",pre)

pre = tag.previous.previous
print ("Previous:",pre)

Output

<p id="id1">Tutorial</p>
Previous: Python
Previous: <p>Python</p>

Example 3

In the next example, we try to determine the element next to <input> tag whose id attribute is 'age'

from bs4 import BeautifulSoup

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

tag = soup.find('input', id='age')
pre = tag.previous_element.previous
print ("Previous:",pre)

Output

Previous: <input id="nm" name="name" type="text"/>
Advertisements