2013-10-04 79 views
0

我正尝试使用函数登录到gmail。我从Excel表传递用户名。问题是我的代码返回值,但没有在文本框中输入。它不会抛出任何错误只是返回null异常。Selenium webdriver在函数中使用时无法识别元素

请帮我这个,我是新的硒webdriver,真的不知道下一步该怎么做,因为它也没有显示任何错误。

public class gmail 
{ 

public static WebDriver driver; 

     public static void main(String[] args) throws IOException, InterruptedException 
{ 
    File file1 = new  File("C:\\Selenium\\IEDriverServer_Win32_2.35.3\\IEDriverServer.exe"); 
    System.setProperty("webdriver.ie.driver", file1.getAbsolutePath()); 
    WebDriver driver = new InternetExplorerDriver(); 
    driver.get("www.gmail.com");  



     FileInputStream file = new FileInputStream(new File("D:\\Automation\\Selenium\\New Folder\\Demo\\Book2.xls")); // Path of the excel where the keywords and data was mentioned 
     HSSFWorkbook workbook = new HSSFWorkbook(file);  
     HSSFSheet sheet = workbook.getSheetAt(0); 
     int d= sheet.getLastRowNum(); 
     System.out.println(d); 


    for (int i=1;i<=d;i++) 
     { 
      Cell cell1=null; 
      cell1=sheet.getRow(i).getCell(0); 
      System.out.println(cell1); 

      if (cell1.getStringCellValue().contains("text"))  
      { 
        Cell cell2=null; 
        cell2=sheet.getRow(i).getCell(1); 
        System.out.println(cell2); 
        stg(cell2); //calling function     

      }  

     }  

} 

public static void stg(Cell cell2) throws InterruptedException 
{ 
    WebElement un1=driver.findElement(By.name("Email")); 
    System.out.println(un1); 
    un1.sendKeys(cell2.getStringCellValue()); 

} 

}

//This is the Output which i am getting: 
1 
text 

seltest10j

Exception in thread "main" java.lang.NullPointerException 
at Excel.gmail.stg(gmail.java:63) 
at Excel.gmail.main(gmail.java:53) 
+0

您在文件gmail.java的第63行有一个null变量,并尝试访问某个方法/字段。这是错误的。 – orique

+0

感谢您的回复。我的代码中的第63行是:WebElement un1 = driver.findElement(By.name(“Email”));我不知道它为什么返回空值。当我在函数外面使用相同的代码时,它将返回适当的值。请给我建议我还能做些什么。你的帮助真的很感激。 – Huma

回答

0

看来你不initalizing类字段driver

public static WebDriver driver;

与此同时,声明一个局部变量具有相同名称main方法中:

WebDriver driver = new InternetExplorerDriver();

是在stg方法里面的代码main时的代码是工作?这将工作,因为局部变量实际上已初始化。当您将代码移到main之外时,局部变量不再隐藏类字段,并且由于您没有初始化它,您将得到一个NullPointerException。

请参阅this以了解有关字段和局部变量的更多信息,请登录this了解有关隐藏字段的信息。

+0

非常感谢你的orique。它在初始化类字段驱动程序后工作。非常感谢你的帮助。现在工作正常。 – Huma

+0

不客气。你能否赞成和/或接受答案?对于其他用户,这将有助于找到一个类似问题的解决方案,我们会提高一点我们的代表:) – orique

0

我强烈建议不要使用Selenium自动化Gmail。它非常复杂,你应该专注于自动化你的OWN应用程序而不是gmail。使用Gmail的POP3服务器来检索电子邮件等这里是我的回答在类似的question

相关问题