用于检查 Selenium WebDriver 中的项目列表的 For 循环

San*_*osh 4 java selenium webdriver selenium-webdriver

我已经写了下面的代码来检查列表 Web 元素,但下面的代码正在运行,但只有第一个项目没有循环到循环结束。

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();
}
Run Code Online (Sandbox Code Playgroud)

Sub*_*ubh 5

@Saifur已经很好地解释了这个问题。所以,我只会放代码让你通过

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(); 
} 
Run Code Online (Sandbox Code Playgroud)

所以,上面我只是稍微调整了您的代码,并在进行更改的地方以及原因进行了相关评论。希望这对你有用。:)