Beautiful Soup - next_siblings Property



Method 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 1

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 wit id attribute as nm

from bs4 import BeautifulSoup

fp = open("index.html")
soup = BeautifulSoup(fp, '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 2

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 3

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 linebreaks in the generator.

Advertisements