繁体   English   中英

显式等待未应用

[英]Explicit wait not getting applied

我正在尝试编写以下代码,但我得到了NoSuchElementException 我看到没有应用显式等待。

WebDriver driver = WebDriverManager.chromedriver().create();
driver.manage().window().maximize();
driver.get("abc");
driver.findElement(By.id("-signin-username")).sendKeys("pratik.p@feg.com");
driver.findElement(By.id("-signin-password")).sendKeys("abcdf");
driver.findElement(By.id("-signin-submit")).click();
// wait(100);
waitForElementToLoad(driver, driver.findElement(By.cssSelector("portal-application[title='AW Acc']")), 100);

下面是“显式等待”方法。

public static void waitForElementToLoad(WebDriver driver, WebElement element,int seconds) {
    WebDriverWait wait = new WebDriverWait(driver, seconds);
    wait.until(ExpectedConditions.visibilityOf(element));
}

使用强制等待Thread.sleep()代码可以工作,但我不希望代码中有任何强制等待,因为它会减慢执行速度。 任何人都可以帮忙吗? 我在控制台中得到这个:

Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"portal-application[title='AW Acc']"}
  (Session info: chrome=102.0.5005.115)

尝试:

...
driver.findElement(By.id("-signin-submit")).click();

WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("portal-application[title='AW Acc']")));

您捕获异常是因为 webdriver 在检查元素的可见性之前尝试查找元素。 所以它的作用是:

  1. 通过 css 选择器portal-application[title='AW Acc']查找元素
  2. 等待元素可见(它的高度和宽度大于0)

它在第 1 步失败,因为元素还没有在 DOM 中。

如果它不起作用,请尝试 Fluent Waits:

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
        .withTimeout(Duration.ofSeconds(10))
        .pollingEvery(Duration.ofSeconds(10))
        .ignoring(NoSuchElementException.class);

WebElement element = wait.until(new Function<WebDriver, WebElement>() {
    public WebElement apply(WebDriver driver) {
        return driver.findElement(By.cssSelector("portal-application[title='AW Acc']"));
    }
});

此外,以防万一您决定想要它,无论如何都有一种肮脏的方式可以工作:

public static WebElement findMyElement(WebDriver driver, By by, int timeoutSeconds) throws Exception {

    long timeout = System.currentTimeMillis() + (timeoutSeconds * 1000);
    while (true) {
        try {
            return driver.findElement(by);
        } catch (NoSuchElementException nEx) {
            Thread.sleep(50);
            if (System.currentTimeMillis() > timeout) {
                throw new RuntimeException("Still can't find the element..");
            }
        }
    }
}
...
WebElement element = findMyElement(driver, By.cssSelector("portal-application[title='AW Acc']"), 20);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM