2011-02-02 76 views
9

我試圖在Java中使用HtmlUnit登錄到一個網站。首先我輸入用戶名和密碼。之後,我需要從下拉框中選擇一個選項。輸入用戶和密碼似乎已經工作,但是當我嘗試從下拉框中選擇項目時,我收到錯誤。誰能幫我解決這個問題嗎?我的代碼如下:如何在Java中使用HtmlUnit?

import com.gargoylesoftware.htmlunit.WebClient; 
import com.gargoylesoftware.htmlunit.html.HtmlElement; 
import com.gargoylesoftware.htmlunit.html.HtmlOption; 
import com.gargoylesoftware.htmlunit.html.HtmlPage; 
import com.gargoylesoftware.htmlunit.html.HtmlSelect; 


public class homePage { 
    public static void main(String[] args) throws Exception { 

    final WebClient webClient = new WebClient(); 
    final HtmlPage page = webClient.getPage("website name here"); 
    HtmlElement usrname = page.getElementByName("username"); 
    usrname.click(); 
    usrname.type("myusername"); 
    HtmlElement psswrd = page.getElementByName("password"); 
    psswrd.click(); 
    psswrd.type("mypassword"); 
    HtmlSelect select = (HtmlSelect) page.getElementById("cmbProducts"); 
    HtmlOption option = select.getOptionByValue("ITDirect"); 
    select.setSelectedAttribute(option, true); 
    HtmlElement signin = page.getElementByName("SignIn"); 
    signin.click(); 
    System.out.println(page.getTitleText()); 
    webClient.closeAllWindows(); 
    } 
} 
+4

告訴我們你是非常有幫助的到底是什麼錯誤。 – MatrixFrog 2011-02-02 00:20:20

回答

3

下面是HTML單元測試的代碼。

final HtmlSelect select = form.getSelectsByName("select1").get(0); 
final List<HtmlOption> expected = new ArrayList<HtmlOption>(); 
expected.add(select.getOptionByValue("option1")); 
expected.add(select.getOptionByValue("option3")); 

請注意,它們使用getSelectsByName而不是getElementById。

下面是這些單元測試的鏈接,以便您可以看到他們如何使用API​​進行規定。 http://htmlunit.sourceforge.net/xref-test/com/gargoylesoftware/htmlunit/html/HtmlSelectTest.html

3

獲取登錄用戶名和密碼的形式。

這裏有一個例子:

HtmlPage page3; 
    page3 = webClient.getPage("Website"); 
    HtmlForm loginForm = page3.getFormByName("loginForm"); 
    HtmlTextInput username = loginForm.getInputByName("NameofUsernameElement"); 
    HtmlPasswordInput pass = loginForm.getInputByName("NameofPassowordElement"); 
    HtmlSubmitInput b = loginForm.getInputByValue("LoginButtonValue"); 

    username.setValueAttribute("Actualy Username"); 
    pass.setValueAttribute("Actual Password"); 
    HtmlPage page2; 
    page2 = b.click();