Beautiful Soup | next_element property
Start your free 7-days trial now!
In Beautiful Soup, the next_element
property returns the next string
or tag
in the parse tree. We will go through the subtleties of this property using examples.
Examples
Consider the following HTML document:
my_html = """ <p>Alex</p> <p>Bob</p>"""soup = BeautifulSoup(my_html)
Let's get the next_element
of <p>Alex</p>
:
p_alex.next_element
'Alex'
Notice how the inner string is registered as the next element. The takeaway here is that the order goes from tag to inner string.
Let's compute the next_element
of this 'Alex'
string:
p_alex.next_element.next_element
'\n'
The result may be surprising for those who expected to see <p>Bob</p>
. Such a result arises because there is a new line character \n
between <p>Alex</p>
and <p>Bob</p>
. To get to Bob, then, you would need to call the next_element
yet again:
p_alex.next_element.next_element.next_element
<p>Bob</p>
If you just wanted to access the next sibling element, then the better alternative would be to call the find_next_sibling()
method:
p_alex.find_next_sibling()
<p>Bob</p>