如何在 htmlunit 中创建复选框元素?

How to create checkbox element in htmlunit?

我正在尝试使用下面解释的 createElement 方法 link:

http://htmlunit.sourceforge.net/apidocs/com/gargoylesoftware/htmlunit/html/InputElementFactory.html#createElement-com.gargoylesoftware.htmlunit.SgmlPage-java.lang.String-org.xml.sax.Attributes-

为此,我尝试使用以下代码:

HtmlPage page = webClient.getPage("http://...");
HtmlCheckBoxInput checkBox = (HtmlCheckBoxInput) page.createElement("checkbox");

但是createElement方法returns一个HtmlUnknownElement对象。如何创建复选框元素?

以下代码在创建输入文本元素时有效:

HtmlElement tmpCheckBox = (HtmlElement) pageClientInput.createElement("input");

按照此处给出的建议,我尝试了另一种方式:

HtmlElement tmpInput = (HtmlElement) page.createElement("input");
tmpInput.setAttribute("type", "checkbox");
HtmlRadioButtonInput  tmpCheckBox = (HtmlRadioButtonInput) tmpInput;
tmpCheckBox.setChecked(true);

但是我在将 HtmlElement 转换为 HtmlRadioButtonInput 时遇到异常:

java.lang.ClassCastException: com.gargoylesoftware.htmlunit.html.HtmlTextInput cannot be cast to com.gargoylesoftware.htmlunit.html.HtmlRadioButtonInput

我需要一个 HtmlRadioButtonInput 才能使用 setChecked 方法。 HtmlElement 没有可用的 setChecked 方法。

您的 createElement 调用会生成一个 HtmlUnknownElement,因为没有复选框 html 标记。要创建复选框,您必须创建类型为 'checkbox'.

的输入

开始 here 阅读更多关于 html 和复选框的信息。

您的代码将无法运行,因为 HtmlPage.createElement 无法在没有属性的情况下选择正确的元素工厂。您不能通过此方法设置。

您可以通过 InputElementFactory 访问正确的元素工厂并将类型设置为复选框,如下所示。

    WebClient webClient = new WebClient();
    webClient.getOptions().setCssEnabled(false);
    HtmlPage page = webClient.getPage("http://...");

    //Attribute need to decide the correct input factory
    AttributesImpl attributes = new org.xml.sax.helpers.AttributesImpl();
    attributes.addAttribute(null, null, "type", "text", "checkbox");
    // Get the input factory instance directly or via HTMLParser, it's the same object 
    InputElementFactory elementFactory = com.gargoylesoftware.htmlunit.html.InputElementFactory.instance; // or HTMLParser.getFactory("input")
    HtmlCheckBoxInput checkBox = (HtmlCheckBoxInput) elementFactory.createElement(page, "input", attributes);
    // You need to add to an element on the page
    page.getBody().appendChild(checkBox);
    //setChecked like other methods return a new Page with the changes
    page = (HtmlPage) checkBox.setChecked(false);