使用 WebDriverWait 和 ExpectedConditions 等待 WebElement 很方便。
问题是,如果 WebElement.findElment 是定位元素的唯一可能方式,因为它没有 ID、没有名称、没有唯一类,那会怎样?
WebDriverWait 的构造函数只接受 WebDriver 作为参数,不接受 WebElement。
我已经设置了 implicitlyWait 时间,所以使用 try{} catch(NoSuchElementException e){} 似乎不是个好主意,因为我不这样做不想为这个元素等待那么长时间。
场景如下:
有一个网页的表单包含许多 input 标签。每个 input 标签都有格式要求。
当不满足格式要求时,动态div标签将出现在这个input标签之后。
由于 input 标签太多,我创建了一个通用方法,例如:
public WebElement txtBox(String name) {
return driver.findElement(By.name(name));
}
而不是为每个 input 标签创建一个数据成员。
然后我创建了一个方法 isValid 来检查某些 input 中的用户输入是否有效。我在 isValid 中应该做的就是检查 inputboxToCheck 之后是否存在 div 标签,代码如下:
public boolean isValid(WebElement inputboxToCheck) {
WebElementWait wait = new WebElementWait(inputboxToCheck, 1);
try {
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("./following-sibling::div")));
return false;
} catch (TimeOutException e) {
return true;
}
}
WebElementWait 是一个虚构的(不存在的)类,其工作方式与 WebDriverWait 相同。
最佳答案
上面提到的 WebElementWait 类:
package org.openqa.selenium.support.ui;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.NotFoundException;
import org.openqa.selenium.WebElement;
public class WebElementWait extends FluentWait<WebElement> {
public final static long DEFAULT_SLEEP_TIMEOUT = 500;
public WebElementWait(WebElement element, long timeOutInSeconds) {
this(element, new SystemClock(), Sleeper.SYSTEM_SLEEPER, timeOutInSeconds, DEFAULT_SLEEP_TIMEOUT);
}
public WebElementWait(WebElement element, long timeOutInSeconds, long sleepInMillis) {
this(element, new SystemClock(), Sleeper.SYSTEM_SLEEPER, timeOutInSeconds, sleepInMillis);
}
protected WebElementWait(WebElement element, Clock clock, Sleeper sleeper, long timeOutInSeconds,
long sleepTimeOut) {
super(element, clock, sleeper);
withTimeout(timeOutInSeconds, TimeUnit.SECONDS);
pollingEvery(sleepTimeOut, TimeUnit.MILLISECONDS);
ignoring(NotFoundException.class);
}
}
它与 WebDriverWait 相同,只是将 WebDriver 参数替换为 WebElement。
然后,isValid 方法:
//import com.google.common.base.Function;
//import org.openqa.selenium.TimeoutException;
public boolean isValid(WebElement e) {
try {
WebElementWait wait = new WebElementWait(e, 1);
//@SuppressWarnings("unused")
//WebElement icon =
wait.until(new Function<WebElement, WebElement>() {
public WebElement apply(WebElement d) {
return d.findElement(By
.xpath("./following-sibling::div[class='invalid-icon']"));
}
});
return false;
} catch (TimeoutException exception) {
return true;
}
}
关于java - Selenium WebDriver : wait for element to be present when locating with WebDriver. findElement 是不可能的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19851518/