Java HTMLUnit在基本示例中有许多错误
我试图得到一个使用HTMLUnit的基本示例 我正在尝试获取此代码以在homedepot网站上搜索演练:Java HTMLUnit在基本示例中有许多错误,java,html,htmlunit,Java,Html,Htmlunit,我试图得到一个使用HTMLUnit的基本示例 我正在尝试获取此代码以在homedepot网站上搜索演练: try (final WebClient webClient = new WebClient(BrowserVersion.CHROME)) { // Get the first page final HtmlPage page1 = webClient.getPage("http://www.homedepot.ca"); // Ge
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和值获取的变体,但没有任何运气。有什么建议吗
非常感谢您的任何意见/反馈
编辑:这是错误代码。当我注释掉按钮和文本字段初始化时,错误消失了
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)
艾德暗示了原因。如果您仍然需要帮助,可以使用以下命令获取具有给定类名的按钮:
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());
}
}请发布错误消息!当你看不到错误是什么的时候,你几乎不可能知道是什么触发了一个特定的错误@EdCottrell Thx Ed.已发布错误消息。该页面似乎没有值为
Go
的
元素。我在移动设备上,目前无法检查HTML源代码,但您可以先检查。这是一个带有HTML内容的
,这是一个带有HTML内容的
。但是,您的代码会查找值为Go的
。这些根本不是一回事,这就是为什么会收到错误消息。请尝试getElementsByClassName
。