Anand
Anand

Reputation: 645

How to use for loop for varying ul & li both?

It may be already asked question,but I am unable to find it. Below is the code I am using:

List<WebElement> allElementswithLetter = Driver.driver.findElements(By.xpath("//div[contains(@class,'page-bg clearfix search-locality')]/ul[i]/li"));

here ul is varying in every iteration in for loop, but my script is unable to identify it.

How to solve this issue?

Upvotes: 1

Views: 536

Answers (2)

Saifur
Saifur

Reputation: 16201

Do a nested loop like the following then. First find the ul and then find the li under ul

List<WebElement> uls = driver.findElements(By.xpath("//div[contains(@class,'page-bg clearfix search-locality')]/ul[" + i + "]"));
for (WebElement element: uls){
   List<WebElement> lis = element.findElements(By.xpath("//li"));
   for (int j=0;j<lis.size();j++){
      //do some operation
   }
}

Upvotes: 3

har07
har07

Reputation: 89315

This part of your xpath "ul[i]" will try to find <ul> element having child element <i>. Instead of that, I believe you want the value of variable named i to be concatenated into your xpath.

You could try to achieve the latter via string concatenation like so :

String xpath = "//div[contains(@class,'page-bg clearfix search-locality')]/ul[" + i + "]/li"
List<WebElement> allElementswithLetter = Driver.driver.findElements(By.xpath(xpath));

Upvotes: 3

Related Questions