zoram
zoram

Reputation: 523

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

1). How can I get all element value in array/list?

2). And How I click by value of the element?

<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')]";

//this getSize() method work Correctly.!

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

How can I get all element value in array/list?

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

I tought, i will get String array like "5,10,20,50,75". :-)

My second question is How can we click by div element value or div class Name(ChoiceEntry Choice_{index} )?

Many thanks in advance.

Upvotes: 0

Views: 3279

Answers (3)

optimistic_creeper
optimistic_creeper

Reputation: 2799

Code snippet for getting the list of values:

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

Code snippet for clicking on a selective choice:

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

Upvotes: 1

Akash W
Akash W

Reputation: 371

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

As per your code if above line gives desired list size then use below code to fetch values

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

Upvotes: 1

Gaurang Shah
Gaurang Shah

Reputation: 12920

you will probably have to override the toString method if you want the output using your code.

The simpler approach to achieve what you are trying to do is.

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

Upvotes: 1

Related Questions