如何在htmlunit中创建checkbox元素?

问题描述 投票:0回答:2

我正在尝试使用以下链接中解释的createElement方法:

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方法返回一个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方法可用。

checkbox htmlunit
2个回答
1
投票

您的代码将无法正常工作,因为Html Page.createElement无法选择没有属性的正确Element Factory。你无法通过这种方法设置。

您可以通过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);

1
投票

您的createElement调用生成HtmlUnknownElement,因为没有复选框html标记。要创建复选框,您必须创建一个类型为“复选框”的输入。

启动here以阅读有关html和复选框的更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.