Beautiful Soup - next_sibling Property



Method Description

The HTML tags appearing at the same indentation level are called siblings. The next_sibling property of the PageElement returns next tag at the same level, or under the same parent.

Syntax

element.next_sibling

Return type

The next_sibling property returns a PageElement, a Tag or a NavigableString object.

Example 1

The index.html wage page consists of a HTML form with three input elements each with a name attribute. In the following example, the next sibling of an input tag with name attribute as nm is located.

from bs4 import BeautifulSoup

fp = open("index.html")
soup = BeautifulSoup(fp, 'html.parser')
tag = soup.find('input', {'name':'age'})
print (tag.find_previous())
from bs4 import BeautifulSoup

fp = open("index.html")
soup = BeautifulSoup(fp, 'html.parser')
tag = soup.find('input', {'id':'nm'})
sib = tag.next_sibling
print (sib)

Output

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

Example 2

In the next example, we have a HTML document with a couple of tags inside a <p> tag. The next_sibling property returns the tag next to <b> tag in it.

from bs4 import BeautifulSoup 

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

tag1 = soup.b 
print ("next:",tag1.next_sibling)

Output

next: <i>Python</i>

Example 3

Consider the HTML string in the following document. It has two <p> tags at the same level. The next_sibling of first <p> should give the second <p> tag's contents.

html = '''
<p><b>Hello</b><i>Python</i></p>
<p>TutorialsPoint</p>
'''
soup = BeautifulSoup(html, 'html.parser')

tag1 = soup.p
print ("next:",tag1.next_sibling)

Output

next:

The blank line after the word next: is unexpected. But that's because of the \n character after the first <p> tag. Change the print statement as shown below to obtain the contents of the next_sibling

tag1 = soup.p
print ("next:",tag1.next_sibling.next_sibling)

Output

next: <p>TutorialsPoint</p>
Advertisements