WebDriver - 使用 Java 等待元素 [英] WebDriver - wait for element using Java
问题描述
我正在寻找类似于 waitForElementPresent
的东西来检查元素是否在我单击之前显示.我认为这可以通过 implicitWait
来完成,所以我使用了以下内容:
I'm looking for something similar to waitForElementPresent
to check whether element is displayed before I click it. I thought this can be done by implicitWait
, so I used the following:
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
然后点击
driver.findElement(By.id(prop.getProperty(vName))).click();
不幸的是,有时它会等待元素,有时则不会.我找了一会儿,找到了这个解决方案:
Unfortunately, sometimes it waits for the element and sometimes not. I looked for a while and found this solution :
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 秒后超时.
And it waited all right, but before timing out it had to wait 10 times 5, 50 seconds. A bit much. So I set the implicitly wait to 1sec and all seemed fine until now. Because now some things wait 10s before timeout but some other things time out after 1s.
您如何涵盖代码中存在/可见的等待元素?任何提示都是可观的.
How do you cover the waiting for element present/visible in your code? Any hint is appreciable.
推荐答案
这就是我在代码中的做法.
This is how I do it in my code.
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 用于其各种构造函数.
- org.openqa.selenium.support.ui.ExpectedConditions for similar shortcuts for various wait scenarios.
- org.openqa.selenium.support.ui.WebDriverWait for its various constructors.
这篇关于WebDriver - 使用 Java 等待元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!