【发布时间】:2018-01-29 09:37:51
【问题描述】:
public class SearchCity {
public void tc() throws InterruptedException, IOException {
System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.navigate().to("http://localhost/allmapview/");
Thread.sleep(3000);
ArrayList<String> data0 = readExcelData(0);
ArrayList<String> data1 = readExcelData(1);
for(int i=0; i<data0.size(); i++) {
driver.findElement(By.xpath(".//*[@id='from']")).sendKeys(data0.get(i));
Thread.sleep(3000);
driver.findElement(By.xpath(".//*[@id='to']")).sendKeys(data1.get(i));
Thread.sleep(3000);
driver.findElement(By.xpath(".//*[@id='calculate-route']/div[3]/div/div[2]/button")).click();
Thread.sleep(8000);
String strText = driver.findElement(By.id("google_dt")).getText();
String strText1 = driver.findElement(By.id("mmi_dt_2")).getText();
FileInputStream fis = new FileInputStream(new File("D:\\Screenshots\\Book1.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook (fis);
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFRow row = sheet.getRow(1);
XSSFCell cell = row.getCell(2);
cell.setCellValue(strText);
XSSFRow row2 = sheet.getRow(1);
XSSFCell cell2 = row2.getCell(3);
cell2.setCellValue(strText1);
fis.close();
FileOutputStream fos =new FileOutputStream(new File("D:\\\\Screenshots\\\\Book1.xlsx"));
workbook.write(fos);
fos.close();
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new
File("D:\\Screenshots\\Screen" +i));
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[@id='calculate-route']/div[3]/div/div[3]/input")).click();
Thread.sleep(3000);
}
}
public ArrayList<String> readExcelData(int colNo) throws IOException {
File src = new File("D:\\Screenshots\\Book1.xlsx");
FileInputStream fis = new FileInputStream(src);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet1 = wb.getSheetAt(0);
Iterator<Row> rowIterator = sheet1.iterator();
rowIterator.next();
ArrayList<String> list = new ArrayList<String>();
while(rowIterator.hasNext()) {
list.add(rowIterator.next().getCell(colNo).getStringCellValue());
}
System.out.println("List :::"+list);
return list;
}
public static void main(String[] args) throws IOException, InterruptedException {
// TODO Auto-generated method stub
SearchCity city = new SearchCity();
city.tc();
我编写了一个代码来读取一个 excel 文件来填充网页中的一些条目,我想从该网页中获取一些数据并将其写入我的 excel 表中,但我在不同行的代码中得到了NullPointerException ,我认为这不是一个重复的问题,所以请提出一些答案。
线程“主”java lang NullPointerException 中的异常 在 SearchCity SearchCity tc(SearchCity java:56) 在 SearchCity SearchCity main(SearchCity java:104)
【问题讨论】:
-
@VPK 它的
city.tc();第56行更重要 -
我猜问题出在
FileOutputStream fos =new FileOutputStream(new File("D:\\\\Screenshots\\\\Book1.xlsx")); workbook.write(fos); fos.close(); -
@shivam,您的异常基本上是在
56行抛出的。那行的代码是什么?如果您尝试访问null对象上的元素,请通过调试检查。 -
cell.setCellValue(strText);这是第 56 行
-
给我一个解决方案