如何在Java中使用HtmlUnit?

时间:2011-02-02 00:06:52

标签: 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();
  }
}

2 个答案:

答案 0 :(得分:4)

这是来自HTMLunit的单元测试的代码。

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

答案 1 :(得分: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();