0

我是 phantomjs 驱动程序的新手,我需要使用 phantomjs 无头驱动程序在后台运行我的脚本。
这是我的代码,我得到空指针异常。目前正在使用 selenium 2.32、testNG、phantomjs jar 1.0.3

public class PhantomjsDemo {

public WebDriver driver;

@BeforeMethod
public void setup(){
    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setJavascriptEnabled(true);
    caps.setCapability("takesScreenshot", true);
    caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,"C:\\phantomjs-1.9.2-windows\\phantomjs.exe");
     WebDriver driver = new PhantomJSDriver(caps);
     driver.get("www.google.com");
}

@Test
public void google(){
    driver.findElement(By.xpath("//*[@id='gbqfba']")).getText();
    driver.findElement(By.xpath("//*[@id='gbqfba']")).getSize().getHeight();
    driver.findElement(By.xpath("//*[@id='gbqfba']")).getSize().getWidth();
    driver.findElement(By.xpath("//*[@id='gbqfba']")).click();
}

@AfterMethod
public void close(){
    driver.quit();
}
}
4

1 回答 1

2

你不是Webdriver在 setup() 方法中初始化你的成员变量,而是一个方法变量:

WebDriver driver = new PhantomJSDriver(caps);

将其更改为

this.driver = new PhantomJSDriver(caps);

NPE 应该消失。

于 2013-10-03T11:51:05.953 回答