2012-03-30 64 views
1

我使用@FindBy批註在我的頁面上查找元素。像這樣:Wait.until()與Webdriver PageFactory元素

@FindBy(xpath = "//textarea") 
    public InputBox authorField; 

請幫忙。我想用我的註釋元素等待(ExpectedConditions)。就像這樣:

wait.until(visibilityOfElementLocated(authorField)); 

代替:

wait.until(visibilityOfElementLocated(By.xpath("//textarea"))); 

感謝提前

回答

1
ExpectedConditions.visibilityOf(authorField); 

看看任何預期條件的源代碼。編寫自己的條件非常容易,可以做你想做的一切。

+0

謝謝,我創建了自己的條件和工作! – Arthur 2012-03-30 09:37:49

3

的問題是,服用WebElement通常假定WebElement方法已經發現(他們是正確的PageFactory整理!它就在元素被方法訪問之前就被找到了),即存在於頁面上。當給By一個方法時,你會說「我希望找到它,但我不知道它什麼時候會出現。」

您可以一起選擇使用

wait.until(visibilityOf(authorField)); 

// right after driver is instantiated 
driver.manage().timeouts().implicitlyWait(...); 

應該這樣做只是你想要的方式。

implicitlyWait()documentation說:

指定的時間元素搜索時,如果不立即出現在駕駛員應等待的時間。

當搜索單個元素時,驅動程序應輪詢頁面直到找到元素,或者在拋出NoSuchElementException之前超時過期。搜索多個元素時,驅動程序應輪詢頁面,直到找到至少一個元素或超時已過。

所以,基本上,它每次查找時都會等待一個元素出現。很明顯,這對各種異步請求都有好處。

+0

隱式地等待異步頁面加載?因爲我需要使用它與AJAX? – Arthur 2012-03-30 08:28:55

+0

答案(這是「是」)...編輯到答案中。 :) – 2012-03-30 08:44:37

+0

謝謝!畢竟,帕維爾佐林是對的,甚至要做到這一點,我必須寫我自己的條件。 – Arthur 2012-03-30 09:36:40

1

我知道這個問題已經回答了,前一段時間被問到了,但我想我會提供一個具體的例子來說明如何爲此編寫自己的預期條件。通過創建這個預期條件類:

/** 
* 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而不是做包裝方法,但它有一個私有構造函數,使其無法擴展。這使得包裝方法成爲那些真正想要在一個地方的所有東西的唯一選擇。)

相關問題