我正在寻找类似于 waitForElementPresent
的东西来检查元素是否在我单击之前显示。我认为这可以通过 implicitWait
来完成,所以我使用了以下内容:
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
然后点击
driver.findElement(By.id(prop.getProperty(vName))).click();
不幸的是,有时它会等待元素,有时则不会。我找了一会儿,找到了这个解决方案:
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();
它一直在等待,但在超时之前它必须等待 10 次 5、50 秒。有点多。所以我将隐式等待设置为 1 秒,直到现在一切都很好。因为现在有些事情会在超时前等待 10 秒,而有些事情会在 1 秒后超时。
您如何处理代码中存在/可见的等待元素?任何提示都是显而易见的。
最佳答案
这就是我在代码中的做法。
WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id<locator>));
或
wait.until(ExpectedConditions.elementToBeClickable(By.id<locator>));
准确地说。
另见:
- org.openqa.selenium.support.ui.ExpectedConditions用于各种等待场景的类似快捷方式。
- org.openqa.selenium.support.ui.WebDriverWait为其各种构造函数。
关于java - WebDriver - 使用 Java 等待元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11736027/