Shaheryar Khawar
Shaheryar Khawar

Reputation: 47

Explicit wait for two elements using OR operator in Selenium

I am trying to find either one of the 2 elements in selenium (java). If anyone is found then that should be clicked. following is not working;                                                            

WebDriverWait wait5 = new WebDriverWait(driver, 5);                     
wait5.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@data-period='R6M'] || //span[@title='FYTD']"))).click();   

Upvotes: 1

Views: 1730

Answers (2)

Guy
Guy

Reputation: 50864

The xpath is invalid, or is a single |

wait5.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@data-period='R6M'] | //span[@title='FYTD']"))).click();

You can also use ExpectedConditions.or fo this

wait5.until(ExpectedConditions.or(
    ExpectedConditions.elementToBeClickable(By.xpath("//a[@data-period='R6M']")),
    ExpectedConditions.elementToBeClickable(By.xpath("//span[@title='FYTD']"))));

To get WebElement from one of two conditions you can build your own implementation

public ExpectedCondition<WebElement> customCondition(By... locators) {
    @Override
    public WebElement apply(WebDriver d) {
        for (By locator in locators) {
            return ExpectedConditions.elementToBeClickable(locator).apply(d);
        }
    }
}

WebElement element = wait4.until(customCondition(By.xpath("//a[@data-period='R6M']"), By.xpath("//span[@title='FYTD']")));

Upvotes: 1

undetected Selenium
undetected Selenium

Reputation: 193108

To induce WebDriverWait for either one of the 2 elements using Selenium client you can use the following Locator Strategy:

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.or(
    ExpectedConditions.elementToBeClickable(By.xpath("//a[@data-period='R6M']")),
    ExpectedConditions.elementToBeClickable(By.xpath("//span[@title='FYTD']"))
)); 

Reference

You can find a relevant discussion in:

Upvotes: 1

Related Questions