在 Selenium 中使用 OR 运算符显式等待两个元素

Explicit wait for two elements using OR operator in Selenium

我试图找到硒中的两种元素之一 (java)。如果找到任何人,则应该单击它。以下不起作用;

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

xpath无效,或者是单个|

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

你也可以使用 ExpectedConditions.or 来实现这个

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

要从两个条件之一获得 WebElement,您可以构建自己的实现

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']")));

使用 client you can use the following :

为两个元素中的任何一个引入 WebDriverWait
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']"))
)); 

参考

您可以在以下位置找到相关讨论:

  • How to wait for either of the two elements in the page using selenium xpath