等待WebElement与webdriverwait和ExpectedConditions一起出现是很方便的.
问题是,如果WebElement.findElment是唯一可能找到元素的方法,那该怎么办?因为它没有id,没有名字,没有唯一的类?
webdriverwait的构造函数只接受WebDriver作为参数,而不接受WebElement.
我已经设置了隐式等待时间,所以使用try {} catch(NoSuchElementException e){}似乎不是一个好主意,因为我不想等待这个元素的那么长时间.
这是场景:
有一个网页,其中包含一个包含许多输入标签的表单.每个输入标签都有格式要求.
public WebElement txtBox(String name) {
return driver.findElement(By.name(name));
}
而不是为每个输入标签创建数据成员.
然后我创建一个方法isValid来检查某些输入中的用户输入是否有效.我在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;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。