我知道這個問題已經回答了,前一段時間被問到了,但我想我會提供一個具體的例子來說明如何爲此編寫自己的預期條件。通過創建這個預期條件類:
/**
* 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
而不是做包裝方法,但它有一個私有構造函數,使其無法擴展。這使得包裝方法成爲那些真正想要在一個地方的所有東西的唯一選擇。)
謝謝,我創建了自己的條件和工作! – Arthur 2012-03-30 09:37:49