2015-01-20 57 views
0

我需要獲取列表中的所有項目,但我的腳本只顯示第一個項目。請參閱for循環中的verifyDisplay斷言,我想在其中顯示列表中的所有項目。謝謝您的幫助。如何獲取列表中的所有項目

我的腳本:

List<WebElement> groups = driver.findElements(By 
      .xpath(".//*[@id='competitiveCategoryTemp']/option")); 

    verifyDisplay("'" + competitive_categories_id_with_space + "'" + "===> The newly added Competitive Category is listed", 
      By.xpath(".//*[@id='competitiveCategoryTemp']/option")); 


    boolean sortedGroups = false; 
    for (int i = 0; i < groups.size() - 1; i++) { 

     verifyDisplay("'" + groups.get(i).getText() + "'" + "\n"+ 
       "Other Competitive Categories are available and names are SORTED", 
       By.xpath(".//*[@id='competitiveCategoryTemp']/option")); 

     if (groups.get(i).getText() 
       .compareToIgnoreCase(groups.get(i + 1).getText()) > 0) { 
      sortedGroups = true; 
      break; 

     } 
     sortedGroups = true; 
    } 

    if (sortedGroups) { 
     System.out.println("The Competitive Category names are SORTED"); 

    } else 
     System.out.println("The Competitive Category names are UN-SORTED"); 

} 
+0

你有沒有設置斷點,並使用調試器? – Ascalonian 2015-01-20 20:19:06

回答

1
if (groups.get(i).getText() 
      .compareToIgnoreCase(groups.get(i + 1).getText()) > 0) { 
     sortedGroups = true; 
     break; 
} 

如果這一條件得到滿足,它打破了的for循環,因此不會繼續前進到第二個元素。這可能是問題嗎?

+0

好抓,GigaStore – familyGuy 2015-01-20 20:21:42

1

WebDriver有選擇類來控制下拉對象。你的方法也行得通。但這樣看起來很整潔,你可以重用現有的方法。

導入這個庫。

import org.openqa.selenium.support.ui.Select; 

然後,

Select dropdown = new Select(driver.findElement(By.id("competitiveCategoryTemp"))); 

dropdown.getOptions() // will return all the options - it is a List<WebElement> 

//To use 
for(WebElement option: dropdown.getOptions()){ 
    System.out.println(option.getText()); 
} 

dropdown.getAllSelectedOptions() // will return the default selected options - it is a List<WebElement> 
+0

它顯示在輸出中,如果dropdown.getOptioins()........... [[[[[Firefox的Firefox驅動程序:MAC上的火狐(d382c52b-a4b5-ea4c-bb54-969268dd4031) ] - > xpath:.//*[@id='competitiveCategoryTemp']]] – familyGuy 2015-01-20 21:00:24

+0

令人驚歎!什麼是一段代碼! – familyGuy 2015-01-20 21:30:16

相關問題