XPath for All the Previous Sibling Elements in Selenium


Selenium - XPath for all the previous sibling elements

The XPath operator to get all the previous sibling elements of a given element is

"preceding-sibling::*"

The expression following-sibling::* selects all the sibling elements present before our web element of interest.

Pass this XPath operator as selector value to find_elements() method.

find_elements(By.XPATH, "preceding-sibling::*")

The function returns all the previous sibling elements, of given element.

XPath for all the previous sibling elements when element is given

For example, a web element my_element is already given to you, and you want to get all the previous sibling elements preceding to this my_element using XPath, then use the following code.

my_element.find_elements(By.XPATH, "preceding-sibling::*")

Consider the following HTML code.

<div id="parent">
  <div id="child1">This is child 1.</div>
  <div id="child2">This is child 2.</div>
  <div id="child3">This is child 3.</div>
  <div id="child4">This is child 4.</div>
</div>

If my_element is the element with id value equal to "child3", then the previous sibling elements of this element are the div element with id "child2" and "child1".

XPath for all the previous sibling elements when element's id is given

For example, you know only the id of the web element, say my_id, and you would like to get all the previous sibling elements of this element, that are present before this element, using XPath, then use the following code.

driver.find_elements(By.XPATH, "//*[@id='my_id']/preceding-sibling::*")

Replace 'my_id' with the value of the id attribute, whose siblings you want to find out.

Similarly, if any other attribute or locator is given for you to identity the element, you can change the XPath expression to find the node of interest, and get all the previous sibling elements.

Tutorial

Please refer this tutorial Python Selenium Example - Get all the previous sibling elements for an example on how to get all the previous sibling elements for a given element using XPath.

Summary

In this Python Selenium tutorial, we have given instructions on how to build XPath expression to find all the previous sibling elements of a given element, with the help of examples.