2013-10-04 78 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

相關問題