Buras Buras - 26 days ago 13
Java Question

How to check all elements in a <ul> list using Selenium WebDriver?

Is it possible to loop through all the

li
elements of the
<ul> </ul>
. Let's say I have an unknown number of
li
elements, so one way to loop through them would be to impose a
for
loop with a maximum possible number of
li
s, say 100, and impose
try and catch
.

try{
for (int i=0; i<100; i++) {
driver.findElement(By.xpath("//div[@id='...']/ul/li[i]"));
}
}
catch {...}


However, it does not recognize the
i
index? How can I make it recognize it?

Is there any better way?

Answer

Webdriver has findElements API, which can be used for this purpose..

List<WebElement> allElements = driver.findElements(By.xpath("//div[@id='...']/ul/li")); 

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