如何在Java中使用HtmlUnit? [英] How to use HtmlUnit in Java?

查看:134
本文介绍了如何在Java中使用HtmlUnit?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Java中的HtmlUnit登录网站。首先我输入用户名然后输入密码。之后我需要从下拉框中选择一个选项。输入用户和密码似乎工作,但当我尝试从下拉框中选择项目时,我收到错误。谁能帮我解决这个问题?我的代码如下:

I'm trying to use HtmlUnit in Java to log into a website. First i enter the user name then password. After that i need to select an option from a dropdown box. entering the user and password seemed to have worked but when i try to select the item from the drop down box i get errors. Can anyone help me fix this? My code is as follows:

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


推荐答案

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

Here's code from the unit tests for 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。

Notice that they use getSelectsByName not getElementById.

这里是这些单元测试的链接,因此您可以看到他们如何使用API​​进行处方。 http://htmlunit.sourceforge.net/xref-test /com/gargoylesoftware/htmlunit/html/HtmlSelectTest.html

Here's a link to those unit tests so you can see how they prescribe using the API. http://htmlunit.sourceforge.net/xref-test/com/gargoylesoftware/htmlunit/html/HtmlSelectTest.html

这篇关于如何在Java中使用HtmlUnit?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆