Beautiful Soup - Functions Reference

Beautiful Soup Useful Resources

Beautiful Soup - next_elements Property



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 - Usage of next_elements property

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 - Fetching all elements after a Tag

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 - Fetching elements after input Tag

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

from bs4 import BeautifulSoup

html = """
<html>
   <head>
      <title>TutorialsPoint</title>
   </head>
   <body>
      <form>
         <input type = 'text' id = 'nm' name = 'name'>
         <input type = 'text' id = 'age' name = 'age'>
         <input type = 'text' id = 'marks' name = 'marks'>
      </form>
   </body>
</html>
"""

soup = BeautifulSoup(html, 'html5lib')

tag = soup.find('input')
nexts = tag.next_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