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();
它等待好了,但在超时之前它必须等待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屋!