【问题标题】:why the below code is printing the first value alone in all iterations?为什么下面的代码在所有迭代中单独打印第一个值?
【发布时间】:2021-10-19 09:37:54
【问题描述】:
List<WebElement> listItems = driver.findElements(By.xpath("//div[@class='inventory_item']"));
System.out.println("Number of Items : " + listItems.size());
         
for(WebElement e : listItems ) 
{
 String sTextValue = e.findElement(By.xpath("//div[@class='inventory_item_name']")).getText();
 System.out.println(sTextValue);
}

在迭代时,它会为每次迭代单独打印第一个项目名称。

【问题讨论】:

    标签: java selenium xpath


    【解决方案1】:

    要使用 XPath 在其他元素中定位元素,您应该在内部元素 XPath 的开头使用点 .,如下所示。
    这应该有效:

    List<WebElement> listItems = driver.findElements(By.xpath("//div[@class='inventory_item']"));
    System.out.println("Number of Items : " + listItems.size());
             
    for(WebElement e : listItems ) 
    {
     String sTextValue = e.findElement(By.xpath(".//div[@class='inventory_item_name']")).getText();
     System.out.println(sTextValue);
    }
    

    【讨论】:

      【解决方案2】:

      你可以这样试一试:

      int i = 0;
      for(WebElement e : listItems) 
      {
          String sTextValue = e.findElement(By.xpath("(//div[@class='inventory_item']//div[@class='inventory_item_name'])['"+i+"']")).getText();
          i++;
          System.out.println(sTextValue);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多