XPath to find sibling elements in Selenium


Python Selenium - XPath for all sibling elements

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

"following-sibling::* | preceding-sibling::*"

The expression following-sibling::* returns all the sibling elements present after our element, and the expression preceding-sibling::* returns all the sibling elements present before our element. OR operator | is joining these two expressions to create an expression that fetches all the sibling elements.

XPath for 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 sibling elements of this element my_element using XPath, then use the following code.

my_element.find_elements(By.XPATH, "following-sibling::* | 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>

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

XPath for sibling elements when element's id is given

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

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

Replace 'myid' 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 the following siblings and preceding siblings.

Tutorial

Please refer this tutorial Selenium - Get all sibling elements for an example on how to get the 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 sibling elements of a given element, with the help of examples.