2014-03-28 24 views
1

我正在測試一個網頁,其中的一些內容加載了XMLHttpRequest。在Ajax調用之後,我需要檢查我的<table>是否包含2行(因爲加載時頁面已經包含1行)。如何等待一定數量的行?

我的測試:

@Before 
public void setUp() throws Exception { 
    driver = new FirefoxDriver(); 
    driver.get("http://localhost/index.html"); 
    driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS); 
} 

@Test 
public void testIfPartnerListPageIsPresent() { 
    driver.findElement(By.id("123")).click(); 
    List<WebElement> rawList = driver.findElement(By.id("id-213")) 
     .findElements(By.tagName("tr")); 
    assertTrue("More than 1 raw", rawList.size() > 1); 
} 

我怎麼能問硒等待我的表中其他行?

回答

3

這個函數會等到表至少包含給定的行數

public void waitUntilRowPopulates(WebElement element, final int rowCount) { 
     final WebElement table = element; 

     new FluentWait<WebDriver>(driver) 
     .withTimeout(60, TimeUnit.SECONDS) 
     .pollingEvery(10, TimeUnit.MILLISECONDS) 
     .until(new Predicate<WebDriver>() { 

      public boolean apply(WebDriver d) { 
       List<WebElement> rawList = table.findElements(By.tagName("tr")); 
       return (rawList.size() >= rowCount); 
      } 
     }); 
    } 
+0

感謝您的幫助。只有一個問題,編譯給我一個關於'rawCount'參數的錯誤。你確定它可以從這種情況下訪問嗎? – Fractaliste

+1

@Fractaliste:它也應該標記爲「final」。我已經更新了我的答案。 – xyz

+0

很好的答案。比明確實例化一個'FluentWait '更簡潔的方法是使用'WebDriverWait',這與'FluentWait'完全相同。 – toniedzwiedz

0

的下面這段代碼應該有所幫助:

int noOfRowsBeforeAJAXCall = driver.findElement(By.id("id-213")).findElements(By.tagName("tr")).size(); 
int noOfRowsAfterAJAXCall; 

driver.findElement(By.id("123")).click(); 

while(1) 
{ 
    noOfRowsAfterAJAXCall = driver.findElement(By.id("id-213")).findElements(By.tagName("tr")).size(); 

    // Check whether row nos. increased 
    if(noOfRowsAfterAJAXCall>noOfRowsBeforeAJAXCall) 
    break; 

    // Re-check after 1 sec 
    Thread.sleep(1000m); 
} 
+1

當你有其他更好的選擇,如'fluentWait'時,使用'Thread.sleep()'不是一個好主意。此代碼也不會編譯。提示:Thread.sleep()只接受數字 – xyz

0

的網頁,尤其是有很多的人裏面的內容,建議使用JSoup庫來獲取html,解析裏面。這也可以用於同步的目的。

示例代碼:

String pageSource = driver.getPageSource(); 
Document doc = Jsoup.parse(pageSource); 
String someValue = doc.getElementsByAttributeValue("id", "specificValue"); 

JSoup有很多getter方法,允許靈活地找到我們想要的。它也支持CSS查詢。