Selenium WeDriver FluentWait

时间:2017-01-12 14:39:31

标签: java selenium

我的脚本出现问题。我使用Selenium WebDriver来驱动网页,但我经常得到ElementNotFound异常。该页面需要一两秒才能加载。

我的代码如下:

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
            .withTimeout(10, TimeUnit.SECONDS)
            .pollingEvery(1, TimeUnit.SECONDS)
            .ignoring(NoSuchElementException.class);        
    try
    {
        WebElement username =  wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@class='gwt-TextBox']")));
        username.sendKeys(usernameParm);
    }
    catch (Exception e) {

        e.printStackTrace();
    }

在一秒左右之后仍然会抛出异常。然后,如果我通过运行以下代码来测试它:

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
            .withTimeout(10, TimeUnit.SECONDS)
            .pollingEvery(1, TimeUnit.SECONDS)
            .ignoring(NoSuchElementException.class);        
    try
    {
        WebElement username =  wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@class='gwt-TextBox1']")));
        username.sendKeys(usernameParm);
    }
    catch (Exception e) {

        e.printStackTrace();
    }

知道TexBox1不存在,然后抛出相同的异常。它似乎没有等待。在第二个实例中,我希望它超时,而不是抛出ElementNotFoundException。

我的实施可能是错误的。

2 个答案:

答案 0 :(得分:0)

查看我关于此主题的帖子:https://iamalittletester.wordpress.com/2016/05/11/selenium-how-to-wait-for-an-element-to-be-displayed-not-displayed/。那里有代码片段。基本上我的建议不是使用FluentWait,而是使用:

WebDriverWait wait = new WebDriverWait(driver, TIMEOUT);
    ExpectedCondition elementIsDisplayed = new ExpectedCondition<Boolean>() {
    public Boolean apply(WebDriver arg0) {
      try {
         webElement.isDisplayed();
         return true;
      }
      catch (NoSuchElementException e ) {
        return false;
      }
      catch (StaleElementReferenceException f) {
        return false;
      }
        } 
    };
    wait.until(elementIsDisplayed);

使用任何超时值定义TIMEOUT对您来说似乎没问题(我相信您在初始问题中说了10秒)。

答案 1 :(得分:0)

是的,我回答了我自己的问题。找出问题所在。

我导入了java.lang.util.NoSuchElementException

我告诉FluentWait忽略NoSuchElementException

实际抛出的是org.openqa.selenium.NoSuchElementException

一旦我改变它,它似乎工作正常。

在我想出这个之前,我也实现了这个:

for (int i = 0; i< 10; i++){
        if (B_Username){
            break;
        } else {
            try {
                WebElement username = driver.findElement(By.xpath("//*[@class='gwt-TextBox']"));
                B_Username = true;
                username.sendKeys(usernameParm);
            } catch (NoSuchElementException e) {
                System.out.println("Caught exception while locating the username textbox");
                System.out.println(i);
                try { 
                    Thread.sleep(500);
                } catch (InterruptedException ee) {
                    System.out.println("Somthing happened while the thread was sleeping");
                }   
            }
        }
    }

也很好。 也许这会帮助别人另一次。 感谢所有回答的人。

相关问题