Beautiful Soup - next_element Property



Method Description

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

Syntax

Element.next_element

Return value

The next_element and next properties return a tag or a NavigableString appearing immediately next to the current tag.

Example 1

In the document tree parsed from the given HTML string, we find the next_element of the <b> 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.b 
print (tag)
nxt = tag.next_element
print ("Next:",nxt)

nxt = tag.next_element.next_element
print ("Next:",nxt)

Output

<b>Excellent</b>
Next: Excellent
Next: <p>Python</p>

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

Example 2

The BeautifulSoup PageElements also support next property which is analogous to next_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.b 
print (tag)
nxt = tag.next
print ("Next:",nxt)

nxt = tag.next.next
print ("Next:",nxt)

Output

<b>Excellent</b>
Next: Excellent
Next: <p>Python</p>

Example 3

In the next example, we try to determine the element next to <body> tag. As it is followed by a line break (\n), we need to find the next element of the one next to body tag. It happens to be <h1> tag.

from bs4 import BeautifulSoup

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

tag = soup.find('body')
nxt = tag.next_element.next
print ("Next:",nxt)

Output

Next: <h1>TutorialsPoint</h1>
Advertisements