XPath to find next sibling element in Selenium Python

Python Selenium – XPath for the next immediate sibling element

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

"following-sibling::*[1]"

The expression following-sibling::* selects all the sibling elements present after 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, "following-sibling::*[1]")

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

XPath for next sibling element when element is given

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

my_element.find_element(By.XPATH, "following-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 next immediate sibling element is the div element with id "child3".

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

driver.find_element(By.XPATH, "//*[@id='my_id']/following-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 next sibling element.

Tutorial

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

Quiz on Selenium

Q1. What is a web driver in Selenium Python?

Not answered

Q2. Which of the following is not a popular web driver used in Selenium Python?

Not answered

Q3. What is the method used to interact with web elements in Selenium Python?

Not answered

Q4. Which of the following is not a commonly used assertion method 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 👍