XPath for All the Following Sibling Elements in Selenium
Selenium - XPath for all the next following sibling elements
The XPath operator to get all the next following sibling elements of a given element is
"following-sibling::*"
The expression following-sibling::*
selects all the sibling elements present after our element of interest.
Pass this XPath operator as selector value to find_elements() method.
find_elements(By.XPATH, "following-sibling::*")
The function returns all the following sibling elements, of given element.
XPath for all the following 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 following sibling elements next to this my_element
using XPath, then use the following code.
my_element.find_elements(By.XPATH, "following-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 "child2"
, then the following sibling elements of this element are the div element with id "child3"
and "child4"
.
XPath for all the following 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 next sibling elements of this element, that are followed after this element, using XPath, then use the following code.
driver.find_elements(By.XPATH, "//*[@id='my_id']/following-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 following sibling elements.
Tutorial
Please refer this tutorial Python Selenium Example - Get all the next following sibling elements for an example on how to get all the next adjacent 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 next following sibling elements of a given element, with the help of examples.