我正在尝试使用Selenium Webdriver从本地存储中获取项目。
我关注this site但是当我运行代码时,我得到了NullPointerException
。
当我调试代码时,我看到函数:getItemFromLocalStorage由于某种原因返回NULL。
这是我的代码:
public class storage
{
public static WebDriver driver;
public static JavascriptExecutor js;
public static void main(String[] args)
{
System.setProperty("webdriver.chrome.driver", "D://chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://html5demos.com/storage");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.id("local")).sendKeys("myLocal");
driver.findElement(By.id("session")).sendKeys("mySession");
driver.findElement(By.tagName("code")).click(); // just to escape textbox
String sItem = getItemFromLocalStorage("value");
System.out.println(sItem);
}
public static String getItemFromLocalStorage(String key)
{
return (String) js.executeScript(String.format(
"return window.localStorage.getItem('%s');", key));
}
}
答案 0 :(得分:1)
那是因为你忘了正确地实例化js
个对象。在driver = new ChromeDriver();
之后添加以下行。
js = ((JavascriptExecutor)driver);
它会起作用。
答案 1 :(得分:0)
我假设你的驱动程序实例上有NPE。 您可以在创建驱动程序实例时设置驱动程序位置属性:
final ChromeDriverService chromeDriverService = new ChromeDriverService.Builder()
.usingDriverExecutable(new File("D://chromedriver.exe")).build();
driver = new ChromeDriver(chromeDriverService);
BTW,我使用了硒2.44.0
答案 2 :(得分:0)
使用此代码
WebStorage webStorage = (WebStorage) new Augmenter().augment(driver);
LocalStorage localStorage = webStorage.getLocalStorage();
String user_data_remember = localStorage.getItem("user_data_remember");
String emailAfterLogout;
String passwordAfterLogout;
if (!user_data_remember.equals("")) {
JSONObject jsonObject = new JSONObject(user_data_remember);
Boolean remember = jsonObject.getBoolean("remember");
if (remember) {
emailAfterLogout = jsonObject.getString("email");
passwordAfterLogout = jsonObject.getString("password");
if (emailAfterLogout.equals(email) && passwordAfterLogout.equals(password)) {
System.out.println("Remember me is working properly.");
} else {
System.out.println("Remember me is not working.");
}
}
} else {
System.out.println("Remember me checkbox is not clicked.");
}