Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in DevOps and Agile by (19.7k points)

In my application when I open page X I expect to see either element A or element B. They are placed in different locations in DOM and can be found using their ids, for example

driver.findElement(By.id("idA"))

How can I ask webdriver to find either A or B?

There are a method driver.findElements(By) which will stop waiting when at least one element is found, but this method forces me to use the same locator for A and B.

What is the proper way to reliably find either A or B, so that I don't have to wait for implicit timeout?

1 Answer

0 votes
by (62.9k points)

Element with id I1 or element with id I2

xpath: //E1[@id=I1] | //E2[@id=I2]

css: css=E1#I1,E2#I2

driver.findElement(By.xpath(//E1[@id=I1] | //E2[@id=I2]))

driver.findElement(By.cssSelector(E1#I1,E2#I2))

don't forget about fluentWait mechanism:

public WebElement fluentWait(final By locator){

        Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)

                .withTimeout(30, TimeUnit.SECONDS)

                .pollingEvery(5, TimeUnit.SECONDS)

                .ignoring(org.openqa.selenium.NoSuchElementException.class);

        WebElement foo = wait.until(

                new Function<WebDriver, WebElement>() {

                    public WebElement apply(WebDriver driver) {

                        return driver.findElement(locator);

                    }

                }

        );

        return  foo;

};

IMHO solution to your issue be like:

fluentWait(By.xpath(//E1[@id=I1] | //E2[@id=I2]));

fluentWait(By.cssSelector(E1#I1,E2#I2))

Browse Categories

...