首頁 > Java > java教程 > 點擊之前如何可靠地等待 WebDriver 中的元素可見性?

點擊之前如何可靠地等待 WebDriver 中的元素可見性?

Mary-Kate Olsen
發布: 2024-11-27 05:58:10
原創
375 人瀏覽過

How to Reliably Wait for Element Visibility in WebDriver Before Clicking?

WebDriver:等待元素存在

問題:如何可靠地等待元素變得可見單擊它?單獨的隱式等待看起來不一致。

為了解決這個問題,可以使用隱式等待。然而,更可靠的解決方案是:

for (int second = 0;; second++) {
    Thread.sleep(sleepTime);
    if (second >= 10)
        fail("timeout : " + vName);
    try {
        if (driver.findElement(By.id(prop.getProperty(vName))).isDisplayed())
            break;
    } catch (Exception e) {
        writeToExcel("data.xls", e.toString(), parameters.currentTestRow, 46);
    }
}
driver.findElement(By.id(prop.getProperty(vName))).click();
登入後複製

此程式碼會等待,直到元素可見或達到逾時值。但是,它需要用戶定義等待時間,這可能很不方便。

答案:利用 WebDriver 的明確等待功能來確保可靠地等待元素存在。

以下程式碼示範了建議的方法:

WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id<locator>));
登入後複製

或者,您可以使用:

wait.until(ExpectedConditions.elementToBeClickable(By.id<locator>));
登入後複製

這些方法提供對等待條件的細微控制,消除了自訂睡眠邏輯的需求。

其他資源:

  • [預期條件](https://seleniumhq.github.io/selenium/javadoc/3.141.59/org/openqa /selenium/support/ui/ExpectedCondit ions.html)
  • [WebDriverWait](https://seleniumhq.github.io/selenium/javadoc/3.141.59/org/openqa/selenium/support/ui/WebDriverWait.html)

以上是點擊之前如何可靠地等待 WebDriver 中的元素可見性?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板