Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advance navigation in selenium webdriver

i have the following HTML

  <div id="element1">welcome</div>
  <div>username</div>

Now the problem is, i have to select the next div element next to "element1". I know,i can build xpath from their parent. But it i need to pick one which is very next to an element. How it is possible ?

like image 902
Karthikeyan Avatar asked Jan 12 '23 13:01

Karthikeyan


2 Answers

Use the following-sibling axis.

This selects all sibling <div> elements after the element1 node:

id('element1')/following-sibling::div

This selects the first sibling <div> element after the element1 node:

id('element1')/following-sibling::div[1]

This selects the first sibling node after the element1 node iff it's a <div> element:

id('element1')/following-sibling::*[1][local-name(.)='div']

All those three examples will select your element (and maybe some more if there are any more matching), so pick one which suits your intent the most.


Note that you can do all this with a simple CSS selector, too. It's equivalent to the last XPath. And it will be faster.

#element1 + div
like image 178
Petr Janeček Avatar answered Jan 27 '23 11:01

Petr Janeček


You can use the following-sibling:

driver.findElement(By.id("element1")).findElement(By.xpath("./following-sibling::div"));
like image 20
Mark Rowlands Avatar answered Jan 27 '23 11:01

Mark Rowlands