Search code examples
javahtmlunit

Htmlunit - Button cannot be found


I want to click a button with this code ("..." means that it was too long to copy):

<a title="theTitle" id="123654" onclick="..." >Press me!</a>

using Htmlunit. The code I have is:

try (final WebClient webClient = new WebClient()) {

        final HtmlPage page = webClient.getPage("http://pathToURL.html");

        HtmlButton button = (HtmlButton) page.getElementById("123654");

        System.out.println(button);
    }

The problem is that button is null. What is wrong with the code?

Thanks.


Solution

  • From API docs:

    public class HtmlButton extends HtmlElement
    implements DisabledElement, SubmittableElement, FormFieldWithNameHistory Wrapper

    for the HTML element "button".

    <a> is not a button, hence your program can't find it.

    You want to use HtmlAnchor for that.

    public class HtmlAnchor extends HtmlElement

    Wrapper for the HTML element "a".