HTMLUnit基本示例中的许多错误

时间:2015-06-14 03:24:31

标签: java html htmlunit

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

我正在尝试使用此代码在homedepot网站上搜索钻取:

metrics = {'users': {'total': {}}}
results = [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
index = 0
for i in results:
    metrics['users']['total']['month' + str(index)] = results[index][1]
    index = index + 1

根据错误消息判断,按钮和文本字段的代码显示不正确。我尝试过按名称,ID和价值获取的一些变化,但我没有运气。有什么建议吗?

非常感谢任何意见/反馈!

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

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

1 个答案:

答案 0 :(得分:1)

艾德暗示了原因。如果您仍需要帮助,可以使用以下内容获取具有给定类名的Button:

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

}

相关问题