【问题标题】:Explicit wait for two elements using OR operator in Selenium在 Selenium 中使用 OR 运算符显式等待两个元素
【发布时间】:2020-01-15 07:17:26
【问题描述】:

我正在尝试在 selenium (java) 中找到 2 个元素之一。如果找到任何人,则应单击该按钮。以下不起作用;

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

【问题讨论】:

  • 你也可以添加你的html吗?
  • 你遇到了什么错误?

标签: java selenium-webdriver xpath webdriver webdriverwait


【解决方案1】:

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

【讨论】:

  • 当我使用以下内容时,它要求将 webelement 更改为布尔值。虽然我想用作 WebElement 以便可以单击其中的任何一个。请建议; 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']"))));
  • @ShaheryarKhawar ExpectedConditions.or 返回一个布尔值。您可以改用第一个建议。
  • 第一个建议仅在 xpath 的情况下使用,但是当我在 OR 条件下搜索一个 className 和其他元素作为 xpath 时呢?
  • @ShaheryarKhawar 更新我的答案。您也可以随时将 By.className 转换为 xpath。
【解决方案2】:

要使用Selenium 客户端为这两个元素之一诱导WebDriverWait,您可以使用以下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']"))
)); 

参考

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-07
    • 2013-08-06
    • 2020-09-19
    • 2020-03-23
    • 2018-11-27
    • 1970-01-01
    • 2014-11-09
    相关资源
    最近更新 更多