Bishoy Ezzat
Bishoy Ezzat

Reputation: 155

How can I detect an element on the screen because sometimes it come with different formats using selenium java?

I am trying to detect an element that can have different index on the screen, sometimes it can be detected like this (//input[@value='OK'])[1] and sometimes it appears and can be detected with this (//input[@value='OK'])[2] there is no other way to get this element to be unique because multiple elements are developed the same but every time it will appear with a different format, is there anyway to check whether it's detected by 1st or the 2nd index and then press on it. I tried try and catch but it's not working

try{
    while(true) {
        new WebDriverWait(driver, 5)
                .ignoring(ElementNotVisibleException.class, NoSuchElementException.class)
                .until(ExpectedConditions.visibilityOf(driver.findElement(element))))
                .click();
    }
} catch (Exception ignored){ }

Upvotes: 1

Views: 100

Answers (2)

Dumidu Handakumbura
Dumidu Handakumbura

Reputation: 426

Investigate to see if you can write relative xpath that is valid for both scenarios. Failing you can use an xpath conditional operator to combine the two values like //*[@id='notify-containe' or contains(@id,'notify-container')].

Upvotes: 0

Selenium Lover
Selenium Lover

Reputation: 80

Just Try this

if(driver.findElements(By.xpath("xpath1")).size()!=0)
{
 driver.findElement(By.xpath("xpath1")).click
}
else if(driver.findElements(By.xpath("xpath2")).size()!=0)
{
 driver.findElement(By.xpath("xpath2")).click
}

Upvotes: 1

Related Questions