Beautiful Soup | previous_siblings property
Start your free 7-days trial now!
In Beautiful Soup, the previous_siblings property of a tag or a string returns a generator used to iterate over all the previous tags and strings under the same parent.
Examples
Consider the following HTML document:
my_html = """ <div> <p>Alex</p> <p id="bob">Bob</p> </div>"""soup = BeautifulSoup(my_html)
Let's get the previous_siblings of <p id="bob">Bob</p>:
Here, we've used the repr(~) method to escape the newline character so that you can explicitly see '\n' instead of an empty line. To break this down, the previous_sibling of <p id="bob">Bob</p> is a newline character, which might be surprising for those who expected to see <p>Alex</p>. Such a result arises because there is a new line character \n between <p>Alex</p> and <p id="bob">Bob</p>.
If you just wanted to access the previous sibling elements, then the better alternative would be to call the find_previous_siblings() method:
<p>Alex</p>