简体   繁体   中英

Selenium webdriver store webelement in webelement list

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 we = driver...("test"); element.add(0,we);

Why I am getting null pointer exception ( 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,

You setted element to null and then tried to add something to it. You cannot add anything to it as it IS 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.

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.

List albums = driver.findElements(By.cssSelector("._3rte"))

Worked for me.

The selector is of course up to you. The first part is the important bit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM