2011-02-11 43 views
1

我不能實例化HtmlHiddenInput並使用appendChild方法來創建表單對象,因爲前者沒有構造函數。有沒有更好的方法,而不是在JavaScript中這樣做?我想保持JavaScript禁用,以節省資源。在Java HtmlUnit中,如何向表單添加隱藏的輸入?

+0

的HtmlUnit是一個測試框架,而不是一個DOM操縱框架。這是工作的錯誤工具。 – skaffman 2011-02-14 10:26:31

+0

我知道。但我需要做大量的網頁抓取,並且無法找到比支持JavaScript的HtmlUnit更好的東西。屏幕抓取不適合我,太慢了。無論如何,這是我需要一點DOM操作的唯一情況:我只想從第一個請求中注入一個「max-results」參數,以便在第一個結果頁面上獲得更多結果。 – 2011-02-14 11:33:28

回答

0

理想情況下,我想能夠寫(f是一個HtmlForm控件,第一個HtmlPage,BA Web客戶端):

HashMap a = new HashMap(); 
a.put("name", "concealed"); 
a.put("value", "secret"); 
f.appendChild(new HtmlHiddenInput(p,a)); 

但由於HtmlHiddenInput不能被實例化,我不得不對JavaScript的回退,這是更慢和更醜:

bool j = b.isJavaScriptEnabled(); 
if (!j) { b.setJavaScriptEnabled(true); } 

p.executeJavaScript(
    "{" + 
    " var" + 
    "  d = document," + 
    "  i = d.createElement('input');" + 
    " with (i) {" + 
    "  name = 'concealed';" + 
    "  type = 'hidden';" + 
    "  value = 'secret';" + 
    " }" + 
    " d.getElementsByName('form1')[0].appendChild(i);" + 
    "}"); 

if (!j) { b.setJavaScriptEnabled(false); } 

恕我直言,有時過於嚴格的限制擋道。我沒有看到爲什麼應該禁止實例化HtmlHiddenInput的好理由。

+1

如果這是您問題的一部分,請將其添加到問題中 - 請勿將其作爲答案發布。 – skaffman 2011-02-14 10:26:06

2

這是官方的方式來做到這一點:我有HtmlFileInput同樣的問題,並通過InputElementFactory已經找到了解決辦法

// where htmlPage is the current page you're on 
// and internalForm is the form you want to append the field to 
HtmlElement createdElement = htmlPage.createElement("input"); 
createdElement.setAttribute("type", inputName); 
createdElement.setAttribute("name", name); 
createdElement.setAttribute("value", value); 
internalForm.appendChild(createdElement); 
0

HtmlPage page; 
    ... 
    AttributesImpl attrs = new AttributesImpl(); 
    attrs.addAttribute("", "type", "type", "", "hidden"); 
    HtmlElement el = InputElementFactory.instance.createElement(page, "input", attrs); 
    HtmlHiddenInput hiddenInput = (HtmlHiddenInput) el; 
相關問題