Beautiful Soup | next_elements property
Start your free 7-days trial now!
In Beautiful Soup, the
next_elements property of a tag or a string returns a generator used to iterate over all the next strings or tags in the parse tree.
Consider the following HTML document:
my_html = """<p>Alex</p><p>Bob</p>"""soup = BeautifulSoup(my_html)
Let's get the
<p>Alex</p> and loop through the resulting generator:
p_alex = soup.find("p")for element in p_alex.next_elements:print(element)<p>Alex</p>Alex<p>Bob</p>Bob
Notice how the inner string is registered as the next element. The takeaway here is that the order goes from tag to inner string. Furthermore, there is a new line character
<p>Bob</p> which is why we see blank lines in the output.