java – 用于检查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();
}

解决方法

@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(); 
}

所以,上面我稍微调整了一下你的代码并获得相关的评论,其中包含了更改以及原因.希望这对你有用.

相关文章

Java中的String是不可变对象 在面向对象及函数编程语言中,不...
String, StringBuffer 和 StringBuilder 可变性 String不可变...
序列化:把对象转换为字节序列的过程称为对象的序列化. 反序...
先说结论,是对象!可以继续往下看 数组是不是对象 什么是对...
为什么浮点数 float 或 double 运算的时候会有精度丢失的风险...
面试题引入 这里引申出一个经典问题,看下面代码 Integer a ...