Beautiful Soup - previous_elements Property



Method Description

In Beautiful Soup library, the previous_elements property returns a generator object containing the previous strings or tags in the parse tree.

Syntax

Element.previous_elements

Return value

The previous_elements property returns a generator.

Example 1

The previous_elements property returns tags and NavibaleStrings appearing before the <p> tag in the document string below −

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

soup = BeautifulSoup(html, 'html.parser')
tag = soup.find('p', id='id1')

pres = tag.previous_elements
print ("Previous elements:")
for pre in pres:
   print (pre)

Output

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

Example 2

All the elements appearing before the <u> tag are listed below −

from bs4 import BeautifulSoup

html = '''
<p>
<b>Excellent</b><i>Python</i>
</p>
<u>Tutorial</u>
'''
soup = BeautifulSoup(html, 'html.parser')

tag1 = soup.find('u')
print ("previous elements:")
print (list(tag1.previous_elements))

Output

previous elements:
['\n', '\n', 'Python', <i>Python</i>, 'Excellent', <b>Excellent</b>, '\n', <p>
<b>Excellent</b><i>Python</i>
</p>, '\n']

Example 3

The BeautifulSoup object itself doesn't have any previous elements −

from bs4 import BeautifulSoup

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

tag = soup.find('input', id='marks')
pres = soup.previous_elements
print ("Previous elements:")
for pre in pres:
   print (pre.name)

Output

Previous elements:
Advertisements