1

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();   
Guy
  • 46,488
  • 10
  • 44
  • 88

2 Answers2

1

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']")));
Guy
  • 46,488
  • 10
  • 44
  • 88
  • When i use the following, it asks to change webelement to boolean. While i would like to use as WebElement so that anyone of them can be clicked. Please suggest; WebDriverWait wait4 = new WebDriverWait(driver, 5); WebElement element=wait4.until(ExpectedConditions.or( ExpectedConditions.elementToBeClickable(By.xpath("//a[@data-period='R6M']")), ExpectedConditions.elementToBeClickable(By.className("//span[@title='FYTD']")))); – Shaheryar Khawar Jan 16 '20 at 10:24
  • @ShaheryarKhawar `ExpectedConditions.or` return a boolean. You can use the first suggestion instead. – Guy Jan 16 '20 at 10:35
  • First suggestion uses only in case of xpath, but When i am searching for one className and other element as xpath in OR condition then? – Shaheryar Khawar Jan 16 '20 at 10:39
  • @ShaheryarKhawar Update my answer. You can also always translate the `By.className` to xpath. – Guy Jan 16 '20 at 11:36
0

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:

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352