如何获取要点击数组的元素列表 - 只执行一次

时间:2016-10-18 11:45:35

标签: java selenium selenium-webdriver

//此代码将获取前5个元素并显示正确的文本

List <WebElement> allElements = driver.findElements(By.xpath("//html/body/div[1]/section/div/article/div/div[1]/ul/li")); 

    int size = 0;
    if (allElements.size() < 4) {
        size = allElements.size();
    }
    else {
        size = 4;
    }

        for (int i = 0; i <= size; i++) 
          System.out.println(allElements.get(i).getText());
}

我将getText()更改为click(),但它只在数组中再获取一个然后终止。为什么?

List <WebElement> allElements = driver.findElements(By.xpath("//html/body/div[1]/section/div/article/div/div[1]/ul/li")); 

    int size = 0;
    if (allElements.size() < 4) {
        size = allElements.size();
    }
    else {
        size = 4;
    }

        for (int i = 0; i <= size; i++) 
                allElements.get(i).click();
}

应该说这是为了测试分页,但我不想超过4页,因为测试它的一些区域可能会有大量的页面。

1 个答案:

答案 0 :(得分:0)

实际上我通过使用javascript执行器来实现它。这是代码:

// Test pagination
        List <WebElement> allElements = driver.findElements(By.xpath("//html/body/div[1]/section/div/article/div/div[1]/ul/li")); 

        int size = 0;
        if (allElements.size() < 4) {
            size = allElements.size();
        }
        else {
            size = 4;
        }

        for (int i = 0; i <= size; i++) {
            pageLinks[i] = "/html/body/div[1]/section/div/article/div/div/ul/li[" + allElements.get(i).getText() + 
                "]/a";
            System.out.println(pageLinks [i]);
        }
        for (int i = 1; i <= size; i++) {
            WebElement pageLink = driver.findElement(By.xpath(pageLinks [i]));
            System.out.println(pageLink);
            JavascriptExecutor js = (JavascriptExecutor) driver;
            js.executeScript("arguments[0].click();", pageLink);
            Thread.sleep(2000);
        }