Using next and previous

Similar to traversing through parsed children and parents in the tree, Beautiful Soup also has the support to traverse and iterate elements located previous to and next to the provided criteria.

The properties next and next_element return the immediately parsed content for the selected criteria. We can also append the next and next_element functions to create a chain of code for traversal, as seen in the following code:

print(soup.find('p','story').next)Once upon a time there were three little sisters; and their names wereprint(soup.find('p','story').next.next)<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>print(soup.find('p','story').next_element)Once upon a time there were three little sisters; ...

Get Hands-On Web Scraping with Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.