无法从页面中选择所有复选框,在Web驱动程序中出错?

时间:2016-03-02 10:10:17

标签: selenium checkbox selenium-webdriver

这里我获取了一个页面的所有复选框但是当我尝试下面的代码时它无法选择所有复选框给出错误。这是我的代码

public class AllCheckBoxes {    

    public static void main(String[] args) throws InterruptedException {

        WebDriver driver = new FirefoxDriver();

        driver.get("http://www.flipkart.com/mobiles/pr?p%5B%5D=facets.brand%255B%255D%3DSamsung&sid=tyy,4io&otracker=nmenu_sub_electronics_0_Samsung");

        Thread.sleep(1000);
        try {
            // Option 1
            List<WebElement> CHECKBOXlist = driver.findElements(By.xpath("//input[@type='checkbox']"));

            // Option 2
            //List<WebElement> CHECKBOXlist = driver.findElements(By.cssSelector("[type='checkbox']"));

            System.out.println("Total Check Boxes are avaliable here are: "+CHECKBOXlist.size());

            for (WebElement checkbox : CHECKBOXlist) {
                checkbox.click();
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());

            // Error as: Element is no longer attached to the DOM 
            // For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
        }

        driver.quit();
    }

} 

有人可以指导我怎么做吗?

1 个答案:

答案 0 :(得分:1)

当您尝试与先前页面实例中的Web元素进行交互时,通常会发生陈旧元素异常。也许你正在勾选的其中一个复选框会像重新加载页面一样,如果是这种情况,那么剩下的复选框将会失败。

修改:是的,在访问您尝试在代码中使用的网页后,似乎就是这种情况。我的建议是在XPath中使用索引来一次获取一个复选框:

public class AllCheckBoxes {    

    public static void main(String[] args) throws InterruptedException {

        WebDriver driver = new FirefoxDriver();

        driver.get("http://www.flipkart.com/mobiles/pr?p%5B%5D=facets.brand%255B%255D%3DSamsung&sid=tyy,4io&otracker=nmenu_sub_electronics_0_Samsung");

        Thread.sleep(1000);
        try {
            // Option 1
            List<WebElement> CHECKBOXlist = driver.findElements(By.xpath("//input[@type='checkbox']"));

            // Option 2
            //List<WebElement> CHECKBOXlist = driver.findElements(By.cssSelector("[type='checkbox']"));

            System.out.println("Total Check Boxes are avaliable here are: "+CHECKBOXlist.size());

            // this for loop will account for page loads:
            for (int i = 0; i < CHECKBOXlist.size(); i++) {
                driver.findElement(By.xpath("(//input[@type='checkbox'])[" + (i+1) + "]")).click();
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());

            // Error as: Element is no longer attached to the DOM 
            // For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
        }

        driver.quit();
    }

} 

所以基本上,你将不得不单独找到复选框,而不是一次性找到页面重新加载。