To iterate through the elements of a List
object in Java using Selenium, you can use a for
loop or the for-each
loop.
Here is an example of how you can use a for
loop to iterate through the elements of a List
and print their text:
List<WebElement> elements = driver.findElements(By.cssSelector("css selector")); for (int i = 0; i < elements.size(); i++) { WebElement element = elements.get(i); System.out.println(element.getText()); }
Here is an example of how you can use a for-each
loop to achieve the same result:
List<WebElement> elements = driver.findElements(By.cssSelector("css selector")); for (WebElement element : elements) { System.out.println(element.getText()); }
In both examples, the findElements
method is used to find the elements that match the given CSS selector, and the getText
method is used to retrieve the text of each element.
You can also use the Iterator
class to iterate through the elements of a List
, like this:
List<WebElement> elements = driver.findElements(By.cssSelector("css selector")); Iterator<WebElement> iterator = elements.iterator(); while (iterator.hasNext()) { WebElement element = iterator.next(); System.out.println(element.getText()); }