Alex
Alex

Reputation: 239

Selenium find element next to another one

I need to find an element that is located next to another one depending to an if condition.
For example, I'm trying to retrieve the bottom with the word “Log In & Pay” only if I found the words ‘DANA’ before.
I can find the first element with text DANA in this way, but how can I find then the next botton element with the text “Log In & Pay” ?

driver.findElement(By.xpath ("//*[contains(text(), 'DANA')]"));

Below the Html page: enter image description here

Upvotes: 0

Views: 1074

Answers (3)

Yevhen B
Yevhen B

Reputation: 325

try using nested predicates

//div[span[contains(text(), 'DANA')]]/following-sibling::div[@class='action']/div

Explanation //div[span[contains(text(), 'DANA')]] finds the div which contains span with text DANA following-sibling::div finds the following div at the same level

Upvotes: 1

RJB
RJB

Reputation: 31

Get the span with the desired text, find the closest ancestor div which contains both els, find the el you want from there. i.e.

//span[contains(text(), 'DANA')]
//ancestor::div[@class='web-pay-wallet-inside-wrap']
//div[@class='action']
/div[contains(text()='Log In & Pay')]

Upvotes: 1

Alexey R.
Alexey R.

Reputation: 8676

Selenium 4 introduces relative locators which allow to look up elements in relative position to others. Like:

  • above
  • below
  • right of
  • left of
  • and even "near"

You can find examples here.

Upvotes: 0

Related Questions