我知道这个问题已经得到解答,并且在不久前被问到,但我想我会提供一个具体示例来说明如何为此编写您自己的预期条件。通过创建这个预期条件类:
/**
* Since the proxy won't try getting the actual web element until you
* call a method on it, and since it is highly unlikely (if not impossible)
* to get a web element that doesn't have a tag name, this simply will take
* in a proxy web element and call the getTagName method on it. If it throws
* a NoSuchElementException then return null (signaling that it hasn't been
* found yet). Otherwise, return the proxy web element.
*/
public class ProxyWebElementLocated implements ExpectedCondition<WebElement> {
private WebElement proxy;
public ProxyWebElementLocated(WebElement proxy) {
this.proxy = proxy;
}
@Override
public WebElement apply(WebDriver d) {
try {
proxy.getTagName();
} catch (NoSuchElementException e) {
return null;
}
return proxy;
}
}
那么这将允许你这样做:
wait.until(new ProxyWebElementLocated(authorField));
这就是你真正需要的。但是如果你想更进一步的抽象,你可以创建一个这样的类:
public final class MyExpectedConditions {
private MyExpectedConditions() {}
public static ExpectedCondition<WebElement> proxyWebElementLocated(WebElement proxy) {
return new ProxyWebElementLocated(proxy);
}
}
这将允许你做这样的事情:
wait.until(MyExpectedConditions.proxyWebElementLocated(authorField));
MyExpectedConditions 类对于一个预期条件可能有点矫枉过正,但如果您有多个预期条件,那么拥有它会让事情变得更好。
作为最后一点,对于任何真正想要加倍努力的人,您还可以将方法添加到 MyExpectedConditions 类,将方法包装在 ExpectedConditions 类中,然后您可以获得所有预期条件的东西从一处。 (我建议扩展 ExpectedConditions 而不是使用包装器方法,但它有一个私有构造函数,因此无法扩展。这使得包装器方法成为那些真正想要所有东西都集中在一个地方的人的唯一选择。)