簡體   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