2012-10-08 50 views
1

我正在使用Selenium和Web驅動程序。Selenium:如何定位通知消息等動態元素

我有一個表格可以裝在燈箱裏。現在,當我點擊「提交」。該燈箱被關閉,並在頁面頂部生成一個簡單的通知,幾秒後消失。現在

我的問題是:當我做

driver.findElement(By.xpath(".//*[@id='createCaseBtn']")).click(); // x-path of submit button 

我應如何檢查的通知消息是否出現在UI。

因爲當我做

driver.findElement(By.xpath(".//*[@id='easyNotification']")).getText(); // x-path of easyNotification message 

我表明我,這是無法找到這似乎邏輯上是正確的元素,因爲在那個時候通知消息是不存在的UI。只有在完成AJAX請求(用於表單的子映射)之後,該消息纔會出現在UI上。

請幫忙!!!!

謝謝

回答

3

曾用顯式的等待。它對我來說很好:

顯式等待是您定義的代碼,用於在繼續執行代碼之前等待某種條件發生。最糟糕的情況是Thread.sleep(),它將條件設置爲等待的確切時間段。有一些便利的方法可以幫助您編寫只會根據需要等待的代碼。 WebDriverWait與ExpectedCondition結合是可以實現的一種方式。

WebDriverWait wait = new WebDriverWait(driver, 10); 
WebElement element = wait.until(
    ExpectedConditions.visibilityOfElementLocated(By.id(".//*[@id='easyNotification']"))); 
0

好。當我處理AJAX時,我總是使用流暢的等待方法。 假設你有郵件點擊提交按鈕後appering的定位:從流暢等待的文檔

String xPathMessage= ".//*[@id='easyNotification']"; 

    public WebElement fluentWait(final By locator){ 
      Wait<WebDriver> wait = new FluentWait<WebDriver>(driver) 
        .withTimeout(30, TimeUnit.SECONDS) 
        .pollingEvery(5, TimeUnit.SECONDS) 
        .ignoring(NoSuchElementException.class); 

      WebElement foo = wait.until(
    new Function<WebDriver, WebElement>() { 
       public WebElement apply(WebDriver driver) { 
          return driver.findElement(locator); 
        } 
        } 
    ); 
           return foo;    }  ; 

//simply call the method: 
String text=fluentWait(By.xpath(xPathMessage)).getText(); 

可能對飛配置其超時和輪詢間隔等待接口的實現。 每個FluentWait實例都定義了等待條件的最長時間以及檢查條件的頻率。此外,用戶可以配置等待,以在等待時忽略特定類型的異常,例如在頁面上搜索元素時的NoSuchElementExceptions。

上述方法還對與isElementPresent描述不壞:

public bool isElementPresent(By selector) 
{ 
    return driver.FindElements(selector).Any(); 
} 

,或者:

public bool isElementPresent(By selector) 
{ 
    return driver.FindElements(selector).size()>0; 
} 

希望這對你的作品