2

Page contains several elements (9) with different String values of km. I need to catch an Integer from each element.

<li class="specItem___2u4I4" data-qa-selector="spec-mileage"><span class="specDot___2SwMP">•</span> 21.950 km</li>

My idea is the following, to find a list of elements via Xpath, getText() and put them into a list.

ArrayList<String> abcd = new ArrayList<>();
for (int i = 1; i <= amountOfElements.size(); i++) {
        WebElement e = driver.findElement(By.xpath("(//li[contains(@data-qa-selector, 'spec-mileage')])['" + i + "']"));
        abcd.add(e.getText());
    }
    System.out.println(abcd);

Unfortunately, list always return the first value nine times (by amount of elements). [• 21.950 km, • ... 21.950 km]

How can I get the list that contains values from different elements?

2 Answers2

1

Instead of findElement method you can use findElements. This will return you a list of all web elements matching the passed locator.
Now you can iterate over the list of web elements extracting text from each web element.
Something like this:

List<String> abcd = new ArrayList<>();
List<WebElement> list = driver.findElements(By.xpath("//li[contains(@data-qa-selector, 'spec-mileage')]"));
for (WebElement el:list){
    abcd.add(el.getText());
}
Prophet
  • 32,350
  • 22
  • 54
  • 79
1

To print all the string values of km you can use Java8's stream() and map() and you can use the following locator strategy:

System.out.println(driver.findElements(By.xpath("//li[@data-qa-selector='spec-mileage']")).stream().map(element->element.getText()).collect(Collectors.toList()));
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352