2013-07-08 30 views
3

我正在開發項目,其中一切都保存在事件中,因此服務器需要一些時間來響應新數據。我使用Fluent等待使用ajax的頁面,但是這個不使用任何ajax。所以我想刷新頁面檢查是否有新的項目,如果不再刷新。 Selenium 2如何實現這一目標?硒刷新

我這樣做:

 def accountsAfterCreating = 0 
     while (accountsAfterCreating <= existingAccounts) { 
      driver.navigate().refresh() 
      WebElement table = wait.until(new Function<WebDriver, WebElement>() { 
       public WebElement apply(WebDriver driver) { 
        return driver.findElement(By.className("table")) 
       } 
      }) 
      accountsAfterCreating = table.findElements(By.className("amount")).size() 
     } 

是不是正確的方式?

回答

0

我想出了這樣的答案。這是因爲它是使用封閉

private boolean refreshUntil(Closure<Boolean> condition) { 
    Wait<WebDriver> wait = new FluentWait<WebDriver>(driver) 
     .withTimeout(8, TimeUnit.SECONDS) 
     .pollingEvery(200, TimeUnit.MILLISECONDS) 
     .ignoring(NoSuchElementException) 
    wait.until(new Predicate<WebDriver>() { 
     boolean apply(WebDriver driver) { 
      driver.navigate().refresh() 
      if (condition()) { 
       return true 
      } 
      return false 
     } 
    }) 
    return true 
} 

,並調用此方法

refreshUntil { 
      accountsBeforeCreation + 1 == driver.findElements(By.tagName("tr"))).size() 
     } 
只在常規工作
2

使用明確的等待像這樣在try catch塊

嘗試{

WebElement myDynamicElement = (new WebDriverWait(driver, 10)) 
    .until(ExpectedConditions.presenceOfElementLocated(By.id("myDynamicElement"))); 
}

catch() 

{

driver.navigate().refresh() 
}

2

我通常使用這個方法來等待任何html標籤。我們也可以指定等待時間。

public boolean waitForElement(WebElement ele, String xpath, int seconds) throws InterruptedException{ 
    //returns true if the element appears within the time 
    //false when timed out 
    int t=0; 
    while(t<seconds*10){ 
     if(ele.findElements(By.xpath(xpath)).size()>0) 
      return true; 
     else{ 
      Thread.sleep(100); 
      t++; 
      continue; 
     } 
    }  
    System.out.println("waited for "+seconds+"seconds. But couldn't find "+xpath+ " in the element specified"); 
    return false; 
}