Beautiful Soup - Functions Reference

Beautiful Soup Useful Resources

Beautiful Soup - next_siblings Property



Description

The HTML tags appearing at the same indentation level are called siblings. The next_siblings property in Beautiful Soup returns returns a generator object used to iterate over all the subsequent tags and strings under the same parent.

Syntax

element.next_siblings

Return type

The next_siblings property returns a generator of sibling PageElements.

Example - Usage of next_siblings property

In HTML form code in index.html contains three input elements. Following script uses next_siblings property to collect next siblings of an input element with id attribute as nm

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, 'html.parser')

tag = soup.find('input', {'id':'nm'})
siblings = tag.next_siblings
print (list(siblings))

Output

['\n', <input id="age" name="age" type="text"/>, '\n', <input id="marks" name="marks" type="text"/>, '\n']

Example - Traversing Next Sibling Tags

Let us use the following HTML snippet for this purpose −

Use the following code to traverse next siblings tags.

from bs4 import BeautifulSoup

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

tag1 = soup.b 
print ("next siblings:")
for tag in tag1.next_siblings:
   print (tag)

Output

next siblings:
<i>Python</i>
<u>Tutorial</u>

Example - next sibling of head tag

Next example shows that the <head> tag has only one next sibling in the form of body tag.

html = '''
<html>
   <head>
      <title>Hello</title>
   </head>
   <body>
      <p>Excellent</p><p>Python</p><p>Tutorial</p>
   </body>
   </head>
'''
from bs4 import BeautifulSoup

soup = BeautifulSoup(html, 'html.parser')

tags = soup.head.next_siblings
print ("next siblings:")
for tag in tags:
   print (tag)

Output

next siblings:

<body>
<p>Excellent</p><p>Python</p><p>Tutorial</p>
</body>

The additional lines are because of the line breaks in the generator.

Advertisements