XPath to find the previous sibling element in Selenium Python

Python Selenium – XPath for the previous sibling element

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

"preceding-sibling::*[1]"

The expression preceding-sibling::* returns all the sibling elements present before our element, and [1]that is followed, specifies that we need only one element, and that too immediate element.

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

find_element(By.XPATH, "preceding-sibling::*[1]")

The function returns the first previous immediate sibling element, of given element.

XPath for previous sibling element when element is given

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

my_element.find_element(By.XPATH, "preceding-sibling::*[1]")

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>
Copy

If my_element is the element with id value equal to "child2", then the previous immediate sibling element is the div element with id "child1".

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

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

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 the immediate previous sibling element.

Tutorial

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

Summary

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

Quiz on Selenium

Q1. What is Selenium Python used for?

Not answered

Q2. Which of the following is not a method to wait for a web element to load in Selenium Python?

Not answered

Q3. What is the method used to navigate back to the previous page in Selenium Python?

Not answered

Q4. What is the method used to switch to a different frame in Selenium Python?

Not answered

Q5. What is the method used to clear the text from an input field in Selenium Python?

Not answered
Code copied to clipboard successfully 👍