2014-04-17 113 views
2

我正在使用下面的代码来逐个点击导航链接,直到它通过WebDriver到达尽头,但它会抛出NullPointerException,因为我已经初始化并且仍然面临此问题,请帮助。Selenium WebDriver中的空指针异常

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; 
    } 
} 
+0

附加堆栈跟踪.. – xyz

回答

12

您的问题从这里开始,我相信:

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

您已经声明driver两次。然后使用isElementPresent中未初始化的driver

我认为你可以解决这个问题如下:

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

谢谢,这真是帮了......我没有relize,这是空指针异常的原因。 – user3543626

+2

@ user3543626:关心接受答案呢? :) –