java - 如何在使用 Selenium 驱动程序执行 Foreach 循环时对其进行控制?

标签 java selenium foreach

我尝试通过 foreach 循环检索文本,按照页面顺序。流程是:它打印单行文本,一旦完成,它就会转到第二页并再次开始检索文本。问题是,它多次检索第一页的数据,有时是 2、3、4 次,如何控制它单次执行?

    if (driver.findElement(By.xpath("//button[@ng-click='currentPage=currentPage+1']")).isEnabled()) {

        int ilength = driver.findElements(By.xpath("//input[@ng-attr-id='{{item.attr}}']")).size();

        Outer: for (int i1 = ilength; i1 > 0;) {
            List<WebElement> findData = driver.findElements(By.xpath("//input[@ng-attr-id='{{item.attr}}']"));
            for (WebElement webElement : findData) {
                String printGroupName = webElement.getAttribute("value").toString();
                System.out.println(printGroupName);
                ilength--;
            }

            if (driver.findElement(By.xpath("//button[@ng-click='currentPage=currentPage+1']")).isEnabled()) {
                action.moveToElement(driver.findElement(By.xpath("//button[@ng-click='currentPage=currentPage+1']"))).click().perform();
                page.pagecallingUtility();
                ilength = driver.findElements(By.xpath("//input[@ng-attr-id='{{item.attr}}']")).size();
            } else {
                break Outer;
            }
        }

    } else {
        List<WebElement> findAllGroupName = driver.findElements(By.xpath("//input[@ng-attr-id='{{item.attr}}']"));

        for (WebElement webElement : findAllGroupName) {
            String printGroupName = webElement.getAttribute("value").toString();
            System.out.println(printGroupName);
        }
    }

HTML Page

控制台数据,用于检索信息 Console

最佳答案

您的循环可以简化如下。

boolean newPageOpened = true;
while (newPageOpened) {
    List<WebElement> findData = driver.findElements(By.xpath("//input[@ng-attr-id='{{item.attr}}']"));
    for (WebElement webElement : findData) {
        if (webElement.isDisplayed()) {
            String printGroupName = webElement.getAttribute("value").toString();
            System.out.println(printGroupName);
        }
    }

    WebElement nextButton = driver.findElement(By.xpath("//button[@ng-click='currentPage=currentPage+1']"));
    if (nextButton.isEnabled()) {
        action.moveToElement(nextButton).click().perform();
        page.pagecallingUtility();
    } else {
        newPageOpened = false;
    }
}

至于一遍遍打印第一页的内容,我怀疑当你打开第二页时,第一页的内容根本就隐藏在页面中了。因此,当您使用 driver.findElements(By.xpath("//input[@ng-attr-id='{{item.attr}}']")) 时,隐藏的首页元素是也发现了。简单的解决方案是在打印之前检查元素是否显示。

关于java - 如何在使用 Selenium 驱动程序执行 Foreach 循环时对其进行控制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50014590/

相关文章:

Java8 : "Translate" old ForEach Method into Lambda/Stream

java - 如何为具有不同值的多个标记添加信息窗口适配器?

php - 记录代码接收错误

java - 从广播接收器更新或附加 TextView

python - 元素不可点击(按钮被其他元素阻挡)

python - Selenium python 驱动程序不会一直单击或按下按钮的按键

php - Magento : How to get qty of a specific product in an order item?

PHP 数组键值

java - jar 未找到类

java - 在 TextView 外单击时,Android 编辑文本不会失去焦点