在selenium中,如何单击延迟加载元素的长列表中的所有元素?

时间:2018-04-25 17:16:58

标签: selenium dynamic lazyload

我有什么 - 我正在自动化一个网站,其中有一个很大的元素列表,但没有一次全部加载。比如说我在列表中有200个元素,但此刻只加载了10个元素,而这10个元素中只有5个在屏幕上可见。

我想做什么 - 现在我想逐个选择所有这些元素,点击它们,因为点击元素选择每个前面的复选框(基本上我想要勾选复选框)。所以我将首先选择5个在页面上可见的元素,然后我将向下滚动以选择另一个可见组,就像我明智地想要选择所有200个元素一样。

我面临的问题 - webdriver.findElements(..)方法返回已加载的10个元素的列表。但它不是按照页面上显示元素的顺序返回列表。我正在使用for循环迭代列表并逐个单击元素。

因此,如果单击第6个元素并且未在页面中显示,则页面会滚动直到该元素并单击它,此后如果第2个元素有机会被单击,则页面应向上滚动以单击它,但是由于滚动导致DOM再次加载,因此我得到StaleElementReferenceException。如果我通过查找元素再次在try catch和get元素列表中处理此异常,则不能保证它的顺序正确并且不能解决我的问题。

解决方案?? - 在selenium中是否有任何方法可以获取元素列表以便在页面上显示?或者,请让我知道实现上述情况的方法应该是什么?

非常感谢任何建议。

注意 - JAVA被用作编程语言。

1 个答案:

答案 0 :(得分:0)

如果您还发布了更有助于解释解决方案的HTML。我试图通过做出一些假设给你一个解决方案。 采用示例HTML代码

<div id "checkbox_container>
     <input type="checkbox " id="checkbox1 ">
     <input type="checkbox " id="checkbox1 ">
     <input type="checkbox " id="checkbox1 ">
     <input type="checkbox " id="checkbox1 ">
     .
     .
     .
     <input type="checkbox " id="checkbox1 ">
 </div>

现在编写将给出count可用复选框元素的定位器和一个将选择特定复选框的定位器。

public class SamplePageObjects {
        //This locator will select all available checkboxes
        public static By ALL_CHECK_BOX = By.xpath("//div[@id='checkbox_container']//input");

        //This locator will select the particular element for the given index
        public static getMeExpectedCheckBox(int index, int maxCount) {
            if (index < 0 || index > maxCount) {
                throw new IlleagalArgumentException(index+" is not a valid index");
            }
            return By.xpath("//div[@id='checkbox_container']//input[" + index + "];
        }
    }

现在,编写您的页面类

public class SamplePage{

    //Gives the count of available elements
    public int getCountOfAvailableCheckBox(WebDriver driver){
        return driver.findElements(SamplePageObjects.ALL_CHECK_BOX).size();
    }

    //Selects the specific element
    public void selectWebElement(WebDriver driver,int index){
        driver.findElement(SamplePageObjects.getMeExpectedCheckBox(index).click();
    }

    //Selects all available element one by one
    public void click(){
        int totalCount = getCountOfAvailableCheckBox();
        for(int i=0; i< totalCount-1; i++){
            try{
                selectWebElement(i,totalCount);
            } catch(StaleElementReferenceException e){
                selectWebElement(i,totalCount);
            }
        }
    }

首先获取所有可用复选框的列表。获取计数后,只需将索引值传递给定位器并执行操作。

希望它会对你有所帮助。