2017-01-30 41 views
0

1)。我如何獲得數組/列表中的所有元素值? 2)。我如何點擊元素的值?如何打印多個元素(div)及其值 - Selenium WebDriver in java

<div class="Choice" style="margin-top: -483px;> 
<div class="ChoiceEntry Choice_1"> 5</div> 
<div class="ChoiceEntry Choice_3"> 10</div> 
<div class="ChoiceEntry Choice_2"> 20</div> 
<div class="ChoiceEntry Choice_4"> 50</div> 
<div class="ChoiceEntry Choice_7"> 75</div> 
<div>...</div> 
</div> 

    private static String choiceXPATH = 
".//div[@class='Choice']//div[contains(@class,'ChoiceEntry')]"; 

//此getSize()方法正常工作。

public int getSize() { 
    waitUntilXXXButtonIsVisible(); 
    List<WebElement> count = getDriver().findElements(By.xpath(XPATH)); 
    return count.size(); 
} 

如何獲取數組/列表中的所有元素值?

public String getAllListValue(){ 
    List<WebElement> list = getDriver().findElements(By.xpath(xpath)); 
    return list.toString();; 
} 

我想,我會得到像「5,10,20,50,75」字符串數組。 :-)

我的第二個問題是我們如何點擊div元素值或div類名(ChoiceEntry Choice_ {index})?

非常感謝提前。

回答

1

如果您希望使用代碼輸出,您可能必須重寫toString方法。

更簡單的方法來實現你想要做的是。

List<WebElement> list = driver.findElements(By.xpath(xpath)); 
    Iterator<WebElement> iterator = list.iterator(); 

    List<String> values = new ArrayList<String>(); 
    while (iterator.hasNext()){ 
     WebElement element = iterator.next(); 
     values.add(element.getText()); 
    } 

    System.out.println(values.toString()); 
+0

謝謝,我的結果看起來像這樣。 [10,5,100,75,,,,,,,,],應該有13個元素。我不知道爲什麼一些元素沒有顯示在數組列表中。 – zoram

1
List<WebElement> listOfDivs = getDriver().findElements(By.xpath(xpath)); 

根據你的代碼,如果上面的行給出了所需的列表大小,然後用下面的代碼,以獲取值的列表中取值

for(WebElement element : listOfDivs) 
{ 
    System.out.println(element.getText()); 
} 
+0

謝謝,我的結果看起來像這樣。 [10,5,100,75,,,,,,,,],應該有13個元素。我不知道爲什麼一些元素沒有顯示在數組列表中。 – zoram

+0

嘗試打印list.size()。如果它返回13個元素,那麼它將打印13個值 –

1

代碼片段:

public List<String> getAllListValues(){ 
    List<WebElement> items = driver.findElements(By.cssSelector("div[class^='ChoiceEntry Choice_']")); 
    List<String> valuesOfChoices = new ArrayList<String>(); 
    for(WebElement item : items){ 
     valuesOfChoices.add(item.getText()); 
    } 

    return valuesOfChoices; 
} 

用於點擊選擇性選項的代碼片段:

//position of the choice is not 0-based 
public void getAllListValues(int positionOfTheChoice){ 
    driver.findElement(By.cssSelector("class='ChoiceEntry Choice_"+positionOfTheChoice+"'")).click(); 
} 
+0

謝謝,我會盡快進行測試。順便說一下,當我們有像「ChoiceEntry Choice xxx」這樣的css類時,我想我們更好地使用xpath! :-) – zoram

+1

xpath不是一個更好的解決方案,如果可能,應該避免它:) –

相關問題