Beautiful Soup | previous_sibling property
Start your free 7-days trial now!
In Beautiful Soup, the previous_sibling
property of a tag or a string returns the previous tag or string under the same parent.
Examples
Basic usage
Consider the following HTML document:
my_html = "<p><b>Alex</b><i>is great</i></p>"soup = BeautifulSoup(my_html)
Let's get the previous_sibling
of <i>is great</i>
:
i_tag.previous_sibling
<b>Alex</b>
This tell us that the previous node of <i>is great</i>
is <b>Alex</b>
, which we know is true since <b>Alex</b>
is the previous element under the same p
tag.
If the previous node does not exist, then a None
is returned:
i_tag.previous_sibling.previous_sibling
None
Unexpected behaviour
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_sibling
of <p id="bob">Bob</p>
:
p_bob.previous_sibling
'\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 <b>Alex</b>
and <b>Bob</b>
. To get to Alex, then, you would need to call the previous_sibling
twice:
p_bob.previous_sibling.previous_sibling
<p>Bob</p>
If you just wanted to access the previous element, then the better alternative would be to call the find_previous_sibling()
method:
<p>Alex</p>