基本示例中的 HTMLUnit 许多错误

HTMLUnit Many Error in Basic Example

我正在尝试获取一个使用 HTMLUnit 的基本示例。

我正在尝试获取此代码以在 homedepot 网站上搜索钻头:

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());
    }

从错误消息来看,我的按钮代码和文本字段似乎不正确。我已经尝试了一些通过名称、ID 和值获取的变体,但我没有任何运气。有什么建议吗?

非常感谢comments/feedback!

编辑:这是错误代码。当我注释掉按钮和文本字段初始化时,错误消失了。

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)

Ed 暗示了原因。如果您仍然需要帮助,您可以使用以下方法获取具有给定 class 名称的按钮:

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());
}

}