HTMLUnit Many Error in Basic Example

464 views Asked by At

I'm trying to get a basic example working using HTMLUnit.

I am trying to get this code to search for a drill on the homedepot website:

try (final WebClient webClient = new WebClient(BrowserVersion.CHROME)) {



        // Get the first page
        final HtmlPage page1 = webClient.getPage("http://www.homedepot.ca");

        // Get the form that we are dealing with and within that form, 
        // find the submit button and the field that we want to change.
        final HtmlForm form = page1.getFormByName("search_terms_form");

        final HtmlSubmitInput button = form.getInputByValue("Go");
        final HtmlTextInput textField = form.getInputByName("q");

        // Change the value of the text field
        textField.setValueAttribute("drill");

        // Now submit the form by clicking the button 
        button.click();




        System.out.println(page1.getTitleText());
    }

Judging by the error messages, it appears my code for the button and the textfield are incorrect. I've tried some variations of getting by name, ID, and value but am not having any luck. Any suggestions?

Any comments/feedback is greatly appreciated!

EDIT: Here's the error code. When I comment out the button and textfield initializations, the error goes away.

Exception in thread "main" com.gargoylesoftware.htmlunit.ElementNotFoundException: elementName=[input] attributeName=[value] attributeValue=[Go]
at com.gargoylesoftware.htmlunit.html.HtmlForm.getInputByValue(HtmlForm.java:795)
at HDSearch.main(HDSearch.java:30)
1

There are 1 answers

0
Ahmed Ashour On BEST ANSWER

Ed hinted about the reason. If you still need help, you can use the below to get the Button with a given class name:

try (final WebClient webClient = new WebClient(BrowserVersion.CHROME)) {
    // Get the first page
    final HtmlPage page1 = webClient.getPage("http://www.homedepot.ca");

    // Get the form that we are dealing with and within that form, 
    // find the submit button and the field that we want to change.
    final HtmlForm form = page1.getFormByName("search_terms_form");

    final HtmlElement button = form.getFirstByXPath("//button[@class='search-button']");
    final HtmlTextInput textField = form.getInputByName("q");

    // Change the value of the text field
    textField.setValueAttribute("drill");

    // Now submit the form by clicking the button 
    button.click();
    System.out.println(page1.getTitleText());
}

}