Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop for Checking list of items in Selenium WebDriver

I have written below code for Checking list Web Elements, but below code is running but for only 1st item its no looping to end of loop.

List <WebElement> listofItems = wd.findElements(By.xpath("//*[starts-with(@id,'result_')]//div//div[1]//div//a//img"));

for (int i=1; i<=listofItems.size(); i++)
{
   listofItems.get(i).click();
   wd.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
   System.out.println(i);
   System.out.println("pass");
   wd.navigate().back();
}
like image 227
Santosh Avatar asked Feb 11 '23 04:02

Santosh


1 Answers

@Saifur has explained nicely regarding the issue. So, I will just put the code that will see you through

List <WebElement> listofItems = wd.findElements(By.xpath("//*[starts-with(@id,'result_')]//div//div[1]//div//a//img"));
WebDriverWait wait = new WebDriverWait(wd, 20); //Wait time of 20 seconds

for (int i=1; i<=listofItems.size(); i++)
{ 
    /*Getting the list of items again so that when the page is
     navigated back to, then the list of items will be refreshed
     again */ 
    listofItems = wd.findElements(By.xpath("//*[starts-with(@id,'result_')]//div//div[1]//div//a//img"));

    //Waiting for the element to be visible
    //Used (i-1) because the list's item start with 0th index, like in an array
    wait.until(ExpectedConditions.visibilityOf(listofItems.get(i-1)));

    //Clicking on the first element 
    listofItems.get(i-1).click();
    wd.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    System.out.print(i + " element clicked\t--");
    System.out.println("pass");
    wd.navigate().back(); 
} 

So, above I have just tweaked your code a bit and have the relevant comments where changes are made and why. Hope this works out for you. :)

like image 54
Subh Avatar answered Feb 13 '23 06:02

Subh