javahtml-selecthtmlunit

HtmlUnit select option that is not in a form


Would like to use HtmlUnit to select an option that is not inside a form. Then I need to retrieve the resulting page of course. Here is what I tried:

public String getNewPage() throws Exception {
    try (final WebClient webClient = new WebClient()) {

        webClient.getOptions().setThrowExceptionOnScriptError(false);
        webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
        webClient.getOptions().setPopupBlockerEnabled(true);
        webClient.getOptions().setJavaScriptEnabled(true);

        final HtmlPage page = webClient.getPage(URL);

        HtmlOption option1 = (HtmlOption) page.getElementById("1");
        option1.removeAttribute("selected");
        HtmlOption option5 = (HtmlOption) page.getElementById("5");
        option5.setSelected(true);

        // Some code missing here........

        return newHtmlString;
}

The page updates automatically when an option is clicked. How can I get the new page after the correct option was selected?


Solution

  • What I did was almost correct, but what was missing was following:

        page.refresh();
        return page.asXml();
    

    Then I had another problem to mark a checkbox as checked. Here is what worked for me:

        HtmlCheckBoxInput checkbox = (HtmlCheckBoxInput) page.getElementById("cb4");
        checkbox.setAttribute("checked", "checked");
        checkbox.fireEvent(Event.TYPE_CHANGE);
        page.refresh();
        System.out.println(page.asXml());