2014-10-08 57 views
-1

我試圖從XML中讀取值。然後,在瀏覽器中,我想登錄到Gmail應用程序。那裏我得到NullPointerException在主要方法中獲取NullPointerException

在Eclipse中使用的代碼如下:

import java.io.File; 
import java.io.IOException; 
import java.util.Properties; 

import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
import javax.xml.parsers.ParserConfigurationException; 

import org.openqa.selenium.By; 
import org.openqa.selenium.WebDriver; 
import org.w3c.dom.Document; 
import org.w3c.dom.Element; 
import org.w3c.dom.Node; 
import org.w3c.dom.NodeList; 
import org.xml.sax.SAXException; 


public class A { 

    private static WebDriver driver; 
    Properties p= new Properties(); 
    String url=p.getProperty("url"); 

    public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException { 

     A a = new A(); 
     String url = a.readXML("logindetails","url"); 
     String username = a.readXML("logindetails","username"); 
     String password = a.readXML("logindetails","password"); 
     System.out.println(url); 
     System.out.println(username); 
     System.out.println(password); 
     //use username for webdriver specific actions 
     driver.findElement(By.id("1001")).sendKeys(url); 
    } 

    public String readXML(String searchelement,String tag) throws SAXException, IOException, ParserConfigurationException{ 
     String ele = null; 
     File fXmlFile = new File("D://NewFile.xml"); 
     DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 
     Document doc = dBuilder.parse(fXmlFile); 

     doc.getDocumentElement().normalize(); 

     NodeList nList = doc.getElementsByTagName(searchelement); 


     Node nNode = nList.item(0); 

     if (nNode.getNodeType() == Node.ELEMENT_NODE) { 
      Element eElement = (Element) nNode; 
      ele=eElement.getElementsByTagName(tag).item(0).getTextContent(); 

     } 
     return ele; 
    } 

} 

輸出是:

www.gmail.com 
test 
test123 
Exception in thread "main" java.lang.NullPointerException 
at A.main(A.java:33) 
+0

可能重複[什麼是空指針異常,以及如何解決?(http://stackoverflow.com/questions/ 218384 /什麼是空指針異常和如何做我修復它) – 2014-10-09 06:17:20

回答

2
private static WebDriver driver; 
.... 
driver.findElement(By.id("1001")).sendKeys(url); 

您訪問driver但從未對其進行初始化。

這就是你的NullPointerException

1

初始化driver。對於如:

如果您正在使用Firefox瀏覽器嘗試

WebDriver driver = new FirefoxDriver(); 
+0

它可能是一個'FirefoxDriver'。或者'ChromeDriver'。或者'HtmlUnitDriver'。或者真的有任何'WebDriver'的實現。 – blalasaadri 2014-10-08 08:11:41

+0

得到錯誤,如下所示:JavaScript錯誤:chrome://browser/content/urlbarBindings.xml,第677行:aUrl未定義 – Amirdha 2014-10-08 08:26:57

+0

也許這是firefox和Selenium的版本問題。也許這會幫助你。通過此鏈接https://groups.google.com/forum/#!topic/selenium-users/yX5i1A1fRd0 – 2014-10-08 09:04:19

相關問題