【问题标题】:Java: Cannot Iterate Through WebElement List in SeleniumJava:无法遍历 Selenium 中的 WebElement 列表
【发布时间】:2018-06-02 07:42:08
【问题描述】:

出于某种原因,即使我使用增强的 for 循环遍历列表中的所有元素,这段代码也总是打印列表中第一个元素的标题。

    List<WebElement> elementList = getAllElements(driver);

    String title = "";
    String[] XPath = {"//*[contains(@id,'itemName')]"};


    for (WebElement singleElement : elementList) {

        try {
            title = singleElement.findElement(By.xpath(XPath[0])).getText();
            System.out.println("Title: " + title);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

列表中有 169 个元素具有不同的标题,但不是打印 169 个不同的标题,而是打印第一个标题 169 次。

我做错了什么?

【问题讨论】:

    标签: java selenium for-loop foreach


    【解决方案1】:

    别介意伙计们,我找到了答案,它与绝对与相对 XPath 搜索有关。

    要解决这个问题,你需要做的就是改变:

    String[] XPath = {"//*[contains(@id,'itemName')]"};
    

    到:

    String[] XPath = {".//*[contains(@id,'itemName')]"};
    

    额外的点强制它使用相对 XPath 而不是绝对 XPath。

    我希望这对其他人有所帮助。

    【讨论】:

      猜你喜欢
      • 2018-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多