Selenium webdriver 使用Apache POI时出现空指针异常

Selenium webdriver 使用Apache POI时出现空指针异常,selenium-webdriver,apache-poi,Selenium Webdriver,Apache Poi,我正在尝试从web将值输入excel,有2列9行,这样我就可以从web上获得10种产品的价格和说明。 但是我得到了空指针异常。请任何人帮我清除这个错误 package samples; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; //

我正在尝试从web将值输入excel,有2列9行,这样我就可以从web上获得10种产品的价格和说明。 但是我得到了空指针异常。请任何人帮我清除这个错误

package samples;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

//import org.apache.commons.io.FileUtils;

//import org.apache.poi.hssf.usermodel.HSSFRow;


import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import java.text.ParseException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
//import org.openqa.selenium.OutputType;
//import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;






public class A1  {



      public static  void main(String[] args) throws InterruptedException, ParseException, IOException, EncryptedDocumentException, InvalidFormatException
      {

                System.out.println("selenium");

            WebDriver webdriver = new FirefoxDriver();
            webdriver.manage().window().maximize();
            webdriver.get("http://www.snapdeal.com");
            webdriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            List<WebElement> alllinks = webdriver.findElements(By.tagName("a"));
            int linkcnt = alllinks.size();
            System.out.println("total links=" +linkcnt);

            Actions action = new Actions(webdriver);
            WebElement COG = webdriver.findElement(By.xpath("//span[text()='Computers, Office & Gaming']"));
            WebElement EHD = webdriver.findElement(By.xpath("//span[text()='External Hard Drives']"));
            action.moveToElement(COG).build().perform();
            Thread.sleep(5000);
            EHD.click();

            webdriver.findElement(By.xpath("//label[@for='Capacity_s-1 TB']")).click();
            Thread.sleep(5000);
            webdriver.findElement(By.xpath("//a[contains(text(),'500 GB')]/..")).click();
            Thread.sleep(5000);
            webdriver.findElement(By.xpath("(//span[@class='price-collapse-arrow'])[1]/..")).click();

            WebElement totalitems = webdriver.findElement(By.xpath("//span[@class='category-count']"));
            String totalitemsvalue=totalitems.getText();
            System.out.println(totalitemsvalue);
            String value=totalitemsvalue.replaceAll(" Items","");
            System.out.println(value);

            try{

            List<WebElement> productprice = webdriver.findElements(By.xpath("//div[@class='product-tuple-description']/div[2]"));
            List<WebElement> productTitle = webdriver.findElements(By.xpath("//div[@class='product-desc-rating title-section-collapse']"));
            int count=productprice.size();
            int count1=productTitle.size();
            System.out.println(count);
            System.out.println(count1);

          //int i=9;
        //  int j=9;
           Thread.sleep(2000); 
         for (count=0;count<10;count++)
            {
             productprice = webdriver.findElements(By.xpath("//div[@class='product-tuple-description']/div[2]"));
        //   File srcfile=((TakesScreenshot)webdriver).getScreenshotAs(OutputType.FILE);
        //   FileUtils.copyFile(srcfile, new File("c:\\screenshot.png"));
             Thread.sleep(2000);
             String RupeesValue= productprice.get(count).getText();
             System.out.println(RupeesValue);
             Thread.sleep(2000);
              productTitle = webdriver.findElements(By.xpath("//div[@class='product-tuple-description']/div[1]"));
             Thread.sleep(2000);
              String TitleValue= productTitle.get(count1).getText();
              System.out.println(TitleValue);
              Thread.sleep(2000);

             FileInputStream fis = new FileInputStream("C:\\Users\\aa74231\\Desktop\\abc.xlsx");
            Workbook wb = WorkbookFactory.create(fis);
               Sheet sheet = wb.getSheet("Sheet1");
       //        Sheet sheet1 = wb.getSheet("Sheet1");

               for (int i=0;i<2;i++)
               {
               Row row=sheet.getRow(count);
              // Row row1=sheet.getRow(j);
               Cell cell = row.createCell(count);
              // Cell cell1 = row1.createCell(count1);
            cell.setCellType(cell.CELL_TYPE_STRING);
            //cell1.setCellType(cell1.CELL_TYPE_STRING);
            if(i==0){
            cell.setCellValue(productprice.get(count).getText());
            }
            else
            {
                cell.setCellValue(productTitle.get(count).getText());
            }
            //cell1.setCellValue(productTitle.get(count1).getText());
            FileOutputStream fos=new FileOutputStream("C:\\Users\\aa74231\\Desktop\\abc.xlsx");
            wb.write(fos);
            fos.close();

            wb.close();
            }
          } 




          } catch(Exception e){
                e.printStackTrace();
        }

 }
}
包装样品;
导入java.io.File;
导入java.io.FileInputStream;
导入java.io.FileNotFoundException;
导入java.io.FileOutputStream;
导入java.io.IOException;
//导入org.apache.commons.io.FileUtils;
//导入org.apache.poi.hssf.usermodel.HSSFRow;
导入org.apache.poi.hssf.usermodel.HSSFSheet;
导入org.apache.poi.hssf.usermodel.HSSFWorkbook;
导入org.apache.poi.EncryptedDocumentException;
导入org.apache.poi.openxml4j.exceptions.InvalidFormatException;
导入org.apache.poi.ss.usermodel.Cell;
导入org.apache.poi.ss.usermodel.Row;
导入org.apache.poi.ss.usermodel.Sheet;
导入org.apache.poi.ss.usermodel.工作簿;
导入org.apache.poi.ss.usermodel.WorkbookFactory;
导入java.text.ParseException;
导入java.util.List;
导入java.util.concurrent.TimeUnit;
导入org.openqa.selenium.By;
//导入org.openqa.selenium.OutputType;
//导入org.openqa.selenium.TakesScreenshot;
导入org.openqa.selenium.WebDriver;
导入org.openqa.selenium.WebElement;
导入org.openqa.selenium.firefox.FirefoxDriver;
导入org.openqa.selenium.interactions.Actions;
公共A1级{
公共静态void main(字符串[]args)引发InterruptedException、ParseException、IOException、EncryptedDocumentException、InvalidFormatException
{
System.out.println(“硒”);
WebDriver WebDriver=新的FirefoxDriver();
webdriver.manage().window().maximize();
webdriver.get(“http://www.snapdeal.com");
webdriver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
列出所有链接=webdriver.findElements(按.tagName(“a”));
int linkcnt=alllinks.size();
System.out.println(“总链接数=”+linkcnt);
动作动作=新动作(webdriver);
WebElement COG=webdriver.findElement(By.xpath(//span[text()='Computers,Office&Gaming']);
WebElement EHD=webdriver.findElement(By.xpath(//span[text()='External Hard Drives']);
action.moveToElement(COG.build().perform();
睡眠(5000);
EHD.click();
webdriver.findElement(By.xpath(“//label[@for='Capacity_s-1 TB'])。单击();
睡眠(5000);
webdriver.findElement(By.xpath(“//a[contains(text(),'500GB')]/…))。单击();
睡眠(5000);
webdriver.findElement(By.xpath((//span[@price-collapse-arrow'])[1]/…)。单击();
WebElement totalitems=webdriver.findElement(By.xpath(//span[@class='category-count']);
字符串totalitemsvalue=totalitems.getText();
System.out.println(totalitemsvalue);
String value=totalitemsvalue.replaceAll(“Items”,“Items”);
系统输出打印项次(值);
试一试{
List productprice=webdriver.findElements(By.xpath(“//div[@class='product-tuple-description']]/div[2]”);
List productTitle=webdriver.findElements(By.xpath(“//div[@class='product-desc-rating title section collapse']);
int count=productprice.size();
int count1=productTitle.size();
系统输出打印项次(计数);
系统输出打印项次(计数1);
//int i=9;
//int j=9;
《睡眠》(2000年);

对于(count=0;count首先,您的ProductTitle Xpath没有从列表中获取所有产品名称。我也更新了它

下面的代码运行良好

package samples;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.poi.EncryptedDocumentException; 
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class X
{
@SuppressWarnings("resource")
public static  void main(String[] args) throws InterruptedException,    ParseException, IOException, EncryptedDocumentException, InvalidFormatException
  {
        System.out.println("selenium");

        WebDriver webdriver = new FirefoxDriver();
        webdriver.manage().window().maximize();
        webdriver.get("http://www.snapdeal.com");
        webdriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        List<WebElement> alllinks = webdriver.findElements(By.tagName("a"));
        int linkcnt = alllinks.size();
        System.out.println("total links=" +linkcnt);

        Actions action = new Actions(webdriver);
        WebElement COG = webdriver.findElement(By.xpath("//span[text()='Computers, Office & Gaming']"));
        WebElement EHD = webdriver.findElement(By.xpath("//span[text()='External Hard Drives']"));
        action.moveToElement(COG).build().perform();
        Thread.sleep(5000);
        EHD.click();

        webdriver.findElement(By.xpath("//label[@for='Capacity_s-1 TB']")).click();
        Thread.sleep(5000);
        webdriver.findElement(By.xpath("//a[contains(text(),'500 GB')]/..")).click();
        Thread.sleep(5000);
        webdriver.findElement(By.xpath("(//span[@class='price-collapse-arrow'])[1]/..")).click();
        Thread.sleep(5000);
        WebElement totalitems = webdriver.findElement(By.xpath("//span[@class='category-count']"));

        String totalitemsvalue=totalitems.getText();
        System.out.println(totalitemsvalue);
        String value=totalitemsvalue.replaceAll(" Items","");
        System.out.println(value);


        try
        {

            List<WebElement> productprice = webdriver.findElements(By.xpath("//div[@class='product-tuple-description']/div[2]"));
            List<WebElement> productTitle = webdriver.findElements(By.xpath("//div[@class='product-tuple-description']/div[1]"));
            int count=productprice.size();
            int count1=productTitle.size();
            System.out.println(count);
            System.out.println(count1);

            String[] productPriceList = new String[count];
            String[] productTitleList = new String[count];


            Thread.sleep(2000);
            for(int k =0; k<count; k++)
            {
                System.out.println(productprice.get(k).getText());
                productPriceList[k]=productprice.get(k).getText();

                System.out.println(productTitle.get(k).getText());
                productTitleList[k]=productTitle.get(k).getText();

           }

            File file= new File("C:\\Users\\XX\\Downloads\\snapdeal.xlsx");  // give your file path
            FileInputStream inputStream = new FileInputStream(file);
            Workbook sampleWorkbook=null;
            sampleWorkbook=new XSSFWorkbook(inputStream);
            Sheet sheet = sampleWorkbook.getSheet("Sheet1");

           for(int t=0;t<count;t++)
           {
               Row row = sheet.createRow(t);
               Cell cell = row.createCell(0);    // create column 1
               cell.setCellValue(productPriceList[t].toString());

               Cell cell1 = row.createCell(1);   // create column 2
               cell1.setCellValue(productTitleList[t].toString());

               inputStream.close();
               FileOutputStream outputStream = new FileOutputStream(file);
               sampleWorkbook.write(outputStream);
               System.out.println("Data written to Excel successful");   
               outputStream.close();
        }
   }
        catch(Exception e)
        {
            System.out.println(e);
        }

  }
包装样品;
导入java.io.File;
导入java.io.FileInputStream;
导入java.io.FileOutputStream;
导入java.io.IOException;
导入java.text.ParseException;
导入java.util.List;
导入java.util.concurrent.TimeUnit;
导入org.apache.poi.EncryptedDocumentException;
导入org.apache.poi.openxml4j.exceptions.InvalidFormatException;
导入org.apache.poi.ss.usermodel.Cell;
导入org.apache.poi.ss.usermodel.Row;
导入org.apache.poi.ss.usermodel.Sheet;
导入org.apache.poi.ss.usermodel.工作簿;
导入org.apache.poi.xssf.usermodel.xssf工作簿;
导入org.openqa.selenium.By;
导入org.openqa.selenium.WebDriver;
导入org.openqa.selenium.WebElement;
导入org.openqa.selenium.firefox.FirefoxDriver;
导入org.openqa.selenium.interactions.Actions;
公共X类
{
@抑制警告(“资源”)
公共静态void main(字符串[]args)引发InterruptedException、ParseException、IOException、EncryptedDocumentException、InvalidFormatException
{
System.out.println(“硒”);
WebDriver WebDriver=新的FirefoxDriver();
webdriver.manage().window().maximize();
webdriver.get(“http://www.snapdeal.com");
webdriver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
列出所有链接=webdriver.findElements(按.tagName(“a”));
int linkcnt=alllinks.size();
System.out.println(“总链接数=”+linkcnt);
动作动作=新动作(webdriver);
WebElement COG=webdriver.findElement(By.xpath(//span[text()='Computers,Office&Gaming']);
WebElement EHD=webdriver.findElement(By.xpath(//span[text()='External Hard Drives']);
action.moveToElement(COG.build().perform();
睡眠(5000);
EHD.click();
webdriver.findElement(By.xpath(“//label[@for='Capacity_s-1 TB'])。单击();
睡眠(5000);
webdriver.findElement(By.xpath(“//a[contains(text(),'500GB')]/…))。单击();
睡眠(5000);
webdriver.findElement(By.xpath((//span[@price-collapse-arrow'])[1]/…)。单击();
睡眠(5000);
WebElement totalitems=webdriver.findElement(By.xpath(//span[@class='category-count']);
字符串totalitemsvalue=tota