【问题标题】:How do I wait for an element to be enabled before clicking on it in java selenium?在 java selenium 中单击某个元素之前,如何等待它被启用?
【发布时间】:2021-05-14 00:34:29
【问题描述】:

您好,我对 selenium 很陌生,想知道如何最好地等待元素启用。我正在编写一个测试来下载一份报告,该报告需要在出现下载按钮之前在表格中将状态设置为“完成”。我曾尝试使用 isDisplayed() 函数,但到目前为止它失败了。我还需要计时器是动态的,以便在下载之前一直检查直到报告完成。

public static boolean isElementVisible(WebElement element) throws Exception {

    return element.isDisplayed();
}


public void statusCheck() throws Exception {


    if(Utils.isElementVisible(status)){

        downloadButton.click();
    }
    else{
        wait(100000);
    }

}

【问题讨论】:

    标签: java selenium selenium-webdriver automated-tests webdriverwait


    【解决方案1】:

    您可以改用 WaitDriver。

    WebDriverWait wait = new WebDriverWait(driver, 10);
    wait.until(ExpectedConditions.or(
        ExpectedConditions.visibilityOfElementLocated(By.id("id1")),
        ExpectedConditions.visibilityOfElementLocated(By.id("id2"))
    ));
    

    https://www.selenium.dev/documentation/en/webdriver/waits/ https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html#or-org.openqa.selenium.support.ui.ExpectedCondition

    【讨论】:

      【解决方案2】:

      关于元素的更多信息,如果 wait for an elementstatus to be set at "Complete" 指的是相同的元素或不同的元素将有助于我们构建一个规范回答。

      如果它们都引用相同的WebElement 而不是使用isDisplayed() 进行验证,您需要为elementToBeClickable​(WebElement element) 引入WebDriverWait,您可以使用以下Locator Strategy

      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(element)).click();
      

      注意webelements没有isElementVisible()这样的方法。


      如果它们都引用不同的WebElements,您可以使用and 子句为elementToBeClickable​() 诱导WebDriverWait,并且可以使用以下Locator Strategy

      new WebDriverWait(driver, 10).until(ExpectedConditions.and(
          ExpectedConditions.elementToBeClickable(By.cssSelector("elementAcss")),
          ExpectedConditions.elementToBeClickable(By.xpath("elementBxpath"))
      ));
      

      您可以在How to wait for either of the two elements in the page using selenium xpath找到相关的详细讨论

      【讨论】:

        猜你喜欢
        • 2021-05-12
        • 2022-11-16
        • 2019-09-30
        • 1970-01-01
        • 1970-01-01
        • 2021-07-28
        • 2021-02-05
        • 2012-03-26
        • 1970-01-01
        相关资源
        最近更新 更多