2016-07-06 28 views
1

所以我試圖在HtmlUnit中設置一個元素的文本,但由於某種原因,我不太明白NullPointerException被拋出。顯然這個元素存在於頁面上,並且通過htmlunit找到它!那麼爲什麼setText會拋出一個錯誤?有任何想法嗎?HtmlUnit .setText()拋出一個空指針異常,但元素不爲空

代碼:

String code = "123"; 

HtmlTextInput textElem = (HtmlTextInput)page.getHtmlElementById("gc-redemption-input"); 
System.out.println(textElem); 
textElem.setText(code); 

輸出:

HtmlTextInput[<input type="text" required="" id="gc-redemption-input" name="claimCode" class="gc-redemption-input a-input-text a-span12 a-form-selected" autofocus="autofocus" value="">] 

錯誤:

Exception in thread "main" 
java.lang.NullPointerException 
    at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.hasTopCall(ScriptRuntime.java:3241) 
    at net.sourceforge.htmlunit.corejs.javascript.InterpretedFunction.call(InterpretedFunction.java:102) 
    at com.gargoylesoftware.htmlunit.javascript.host.dom.MutationObserver.attributeReplaced(MutationObserver.java:165) 
    at com.gargoylesoftware.htmlunit.html.HtmlElement.fireHtmlAttributeReplaced(HtmlElement.java:348) 
    at com.gargoylesoftware.htmlunit.html.HtmlElement.fireHtmlAttributeReplaced(HtmlElement.java:353) 
    at com.gargoylesoftware.htmlunit.html.HtmlElement.fireHtmlAttributeReplaced(HtmlElement.java:353) 
    at com.gargoylesoftware.htmlunit.html.HtmlElement.fireHtmlAttributeReplaced(HtmlElement.java:353) 
    at com.gargoylesoftware.htmlunit.html.HtmlElement.fireHtmlAttributeReplaced(HtmlElement.java:353) 
    at com.gargoylesoftware.htmlunit.html.HtmlElement.fireHtmlAttributeReplaced(HtmlElement.java:353) 
    at com.gargoylesoftware.htmlunit.html.HtmlElement.fireHtmlAttributeReplaced(HtmlElement.java:353) 
    at com.gargoylesoftware.htmlunit.html.HtmlElement.fireHtmlAttributeReplaced(HtmlElement.java:353) 
    at com.gargoylesoftware.htmlunit.html.HtmlElement.fireHtmlAttributeReplaced(HtmlElement.java:353) 
    at com.gargoylesoftware.htmlunit.html.HtmlElement.setAttributeNS(HtmlElement.java:209) 
    at com.gargoylesoftware.htmlunit.html.HtmlInput.setAttributeNS(HtmlInput.java:538) 
    at com.gargoylesoftware.htmlunit.html.HtmlTextInput.setAttributeNS(HtmlTextInput.java:164) 
    at com.gargoylesoftware.htmlunit.html.DomElement.setAttribute(DomElement.java:331) 
    at com.gargoylesoftware.htmlunit.html.HtmlInput.setValueAttribute(HtmlInput.java:94) 
    at com.gargoylesoftware.htmlunit.html.HtmlTextInput.setText(HtmlTextInput.java:124) 
+1

現在應該修復。請參閱[Htmlunit填充輸入空指針,但元素沒有空](http://stackoverflow.com/questions/41839518/htmlunit-null-pointer-on-filling-input-but-element-is-not-nulled) – RBRi

回答

1

的問題可能是String code = '123';,因爲這說明我的IDE中出現以下錯誤:Unclosed character literal。嘗試使用雙引號:String code = "123";

+1

謝謝你的好成績!不幸的是,這不是問題,這是我沒有複製過的一行,而是輸入:) – k9b