做循环和预期条件 - 可以一起使用吗?

时间:2017-02-27 10:48:10

标签: java selenium selenium-webdriver webdriver

While While Loop和ExpectedConditions - 可以一起使用吗?

  1. Iam使用下面列出的方法无法找到元素/超时异常。
  2. 2。是否可以添加while循环,以便该方法可以多次检查和执行?

        public void waitAndClickElement(WebElement element) throws InterruptedException {
        try {
            this.wait.until(ExpectedConditions.elementToBeClickable(element)).click();
            System.out.println("Successfully clicked on the WebElement: " + "<" + element.toString() + ">");
        }catch (Exception e) {
            System.out.println("Unable to wait and click on WebElement, Exception: " + e.getMessage());
            Assert.assertFalse(true, "Unable to wait and click on the WebElement, using locator: " + "<" + element.toString() + ">");
        }
    }
    

1 个答案:

答案 0 :(得分:1)

是的,那是可能的。像这样:

    boolean clicked = false;
    int attempts = 0;
    while(!clicked && attempts < 5) {
    try {
            this.wait.until(ExpectedConditions.elementToBeClickable(element)).click();
            System.out.println("Successfully clicked on the WebElement: " + "<" + element.toString() + ">");
            clicked = true;
     } catch (Exception e) {
            System.out.println("Unable to wait and click on WebElement, Exception: " + e.getMessage());
            Assert.assertFalse(true, "Unable to wait and click on the WebElement, using locator: " + "<" + element.toString() + ">");
        }
         attempts++;
    }

对你的while循环添加最大尝试也是一个好主意,这样你就不会陷入无限循环。