簡體   English   中英

如何打印多個元素(div)及其值-Java中的Selenium WebDriver

[英]How to print multiple elements (div) & it values - Selenium WebDriver in java

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

2)。 以及如何按元素的值單擊?

<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”這樣的String數組。 :-)

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

提前謝謝了。

如果要使用代碼輸出,則可能必須重寫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());
List<WebElement> listOfDivs = getDriver().findElements(By.xpath(xpath));

根據您的代碼,如果上面的行給出了所需的列表大小,則使用下面的代碼來獲取值

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

用於獲取值列表的代碼段:

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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM