Beautiful Soup - next_elements Property



Method Description

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

Syntax

Element.next_elements

Return value

The next_elements property returns a generator.

Example 1

The next_elements property returns tags and NavibaleStrings appearing after the <b> 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('b')

nexts = tag.next_elements
print ("Next elements:")
for next in nexts:
   print (next)

Output

Next elements:
Excellent

Python

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

Example 2

All the elements appearing after the <p> 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('p')
print ("Next elements:")
print (list(tag1.next_elements))

Output

Next elements:
['\n', <b>Excellent</b>, 'Excellent', <i>Python</i>, 'Python', '\n', '\n', <u>Tutorial</u>, 'Tutorial', '\n']

Example 3

The elements next to the input tag present in the HTML form of index.html are listed below −

from bs4 import BeautifulSoup

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

tag = soup.find('input')
nexts = soup.previous_elements
print ("Next elements:")
for next in nexts:
   print (next)

Output

Next elements:

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

<input id="marks" name="marks" type="text"/>
Advertisements