java Selenium webdriver 将 webelement 存储在 webelement 列表中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27503823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 11:55:10  来源:igfitidea点击:

Selenium webdriver store webelement in webelement list

javaselenium-webdriver

提问by Karim Narsindani

How to store webelement in webelement list? I have created list for webelement and passing webelement obj in add method, but system display null exception. Java Code: List<WebElement> element=null;and in for loop i am passing webelement obj in add method like: WebElement we = driver...("test"); element.add(0,we);

如何将 webelement 存储在 webelement 列表中?我已经为 webelement 创建了列表并在 add 方法中传递了 webelement obj,但系统显示 null 异常。Java 代码:List<WebElement> element=null;在 for 循环中,我在 add 方法中传递 webelement obj,例如:WebElement we = driver...("test"); element.add(0,we);

Why I am getting null pointer exception (java.lang.NullPointerException)?

为什么我得到空指针异常 ( java.lang.NullPointerException)?

I would appreciate your inputs.

我将不胜感激您的投入。

 public void test(){
 List<WebElement> element = null;

    int rows=1;
    for(int i=1; i<=rows;i++){
        text=driver.findElement(By.xpath("//*[@id='testid']/table/tbody/tr["+i+"]/td/p")).getText();
        if(!text.equals("")){
            for(int j=1;j<=rows;j++){
                if(isElementPresent(driver, By.xpath("//*[@id='testid']/table/tbody/tr["+(j+1)+"]/td[6]/a"))){
                    WebElement we =driver.findElement(By.xpath("//*[@id='testid']/table/tbody/tr["+(j+1)+"]/td[6]/a"));
                    element.add(we);
                    rows++;
                }
            }
        }else{
            break;
        }
    }
    for(WebElement we:element){
        we.click();
        }
    }

Thanks,

谢谢,

采纳答案by Nahuel Ianni

You setted element to null and then tried to add something to it. You cannot add anything to it as it IS null!

您将 element 设置为 null,然后尝试向其中添加一些内容。你不能添加任何东西,因为它是空的!

Instead, try this:

相反,试试这个:

List<WebElement> element=new ArrayList<WebElement>();
...

As you can see, I initialized the object before using it, so it no longer should be null.

如您所见,我在使用对象之前对其进行了初始化,因此它不应再为 null。

回答by Helping Hands

Please replace your following line :

请替换您的以下行:

 WebElement we = driver.findElement(By.xpath("//*[@id='testid']/table/tbody/tr["+(j+1)+"]/td[6]/a"));

With following :

与以下:

 java.util.List<WebElement> element= driver.findElement(By.xpath("//*[@id='testid']/table/tbody/tr["+(j+1)+"]/td[6]/a"));

Also you can get list size using : System.out.println(we.size()); Let me know if any query.

您也可以使用以下方法获取列表大小: System.out.println(we.size()); 如果有任何疑问,请告诉我。