Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null Pointer Exception in Selenium WebDriver

Tags:

selenium

I am using the below code to click on navigation links one by one till it reaches end by using WebDriver but it throw NullPointerException, confused as I have already initialized and still facing this issue, please help.

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;


public class Exercise_dice {
    static WebDriver driver;
    public static void main(String[] args) {
        WebDriver driver=new FirefoxDriver();
        driver.get("http://www.dice.com");
        driver.findElement(By.xpath("//*[@id='FREE_TEXT']")).sendKeys("selenium");
        driver.findElement(By.xpath("//*[@id='searchSubmit']")).click();

        String part1= "//*[@id='yui-main']/div/div[1]/div[1]/div[1]/a[";
        String part2= "]";

        int i=1;
        while(isElementPresent(part1+i+part2)){
            String text= driver.findElement(By.xpath(part1+i+part2)).getText();
            System.out.println(text);
            driver.findElement(By.xpath(part1+i+part2)).click();
            i++;
        }
    }

    public static boolean isElementPresent(String element_xpath){
        int count=driver.findElements(By.xpath(element_xpath)).size();

        if (count == 0)
            return false;
        else 
            return true;
    }
}
like image 922
user3543626 Avatar asked Jul 23 '26 15:07

user3543626


1 Answers

Your issue starts here, I believe:

static WebDriver driver;
public static void main(String[] args) {
    WebDriver driver=new FirefoxDriver();

You've declared driver twice. Then you use the uninitialized driver in isElementPresent.

I think you can fix this as follows:

static WebDriver driver;
public static void main(String[] args) {
    driver=new FirefoxDriver();
like image 196
Richard Avatar answered Jul 25 '26 11:07

Richard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!