为内联代码获取 NullPointerException。我已经在全球范围内定义了 WebDriver,调用浏览器方法工作正常 我在这里做错了什么
getting NullPointerException for inline code. I have defined the WebDriver globally, call browser method is working fine What i am doing wrong here
public class Test{
static WebDriver driver;
public static void main(String[] arg) throws IOException, InterruptedException {
Test2();
}
public static void CallBrowserChrome() {
try {
System.setProperty("webdriver.chrome.driver", "G:\Chrome\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://google.com");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void Test2() throws IOException, InterruptedException {
CallBrowserChrome();
FileInputStream fis = new FileInputStream("G:\Book1.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.getSheetAt(0);
int rows = sheet.getLastRowNum();
System.out.println(rows);
for (int i = 1; i <= rows; i++) {
String value = sheet.getRow(i).getCell(0).getStringCellValue();
System.out.println(value);
**driver.findElement(By.xpath("//*[@id='js-main-container']"))
.sendKeys(value);**
}
}
}
//错误在这一行 Highlighted(driver in 2nd Class);我已经尝试在方法主体内提供 WebDriver,但这也不起作用
[1]: https://i.stack.imgur.com/0GzeA.png
此行:WebDriver driver = new ChromeDriver();
将驱动程序声明为 CallBrowserChrome
的本地驱动程序并忽略您的其他声明。
将您的第一个方法更改为:
public static void CallBrowserChrome() {
try {
System.setProperty("webdriver.chrome.driver", "G:\Chrome\chromedriver.exe");
driver = new ChromeDriver();// update this line
driver.get("https://google.com");
//...etc
public class Test{
static WebDriver driver;
public static void main(String[] arg) throws IOException, InterruptedException {
Test2();
}
public static void CallBrowserChrome() {
try {
System.setProperty("webdriver.chrome.driver", "G:\Chrome\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://google.com");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void Test2() throws IOException, InterruptedException {
CallBrowserChrome();
FileInputStream fis = new FileInputStream("G:\Book1.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.getSheetAt(0);
int rows = sheet.getLastRowNum();
System.out.println(rows);
for (int i = 1; i <= rows; i++) {
String value = sheet.getRow(i).getCell(0).getStringCellValue();
System.out.println(value);
**driver.findElement(By.xpath("//*[@id='js-main-container']"))
.sendKeys(value);**
}
}
}
//错误在这一行 Highlighted(driver in 2nd Class);我已经尝试在方法主体内提供 WebDriver,但这也不起作用
[1]: https://i.stack.imgur.com/0GzeA.png
此行:WebDriver driver = new ChromeDriver();
将驱动程序声明为 CallBrowserChrome
的本地驱动程序并忽略您的其他声明。
将您的第一个方法更改为:
public static void CallBrowserChrome() {
try {
System.setProperty("webdriver.chrome.driver", "G:\Chrome\chromedriver.exe");
driver = new ChromeDriver();// update this line
driver.get("https://google.com");
//...etc