【发布时间】:2017-01-06 03:47:36
【问题描述】:
尝试在名为 TimeEdit 的页面上使用 HTMLUnit,该页面主要用于为学校制定时间表。我想在此处的输入字段中添加一个搜索词(“DV1431”): TimeEdit
然后我想以某种方式提交。我读过您可以使用 HTMLUnit 触发 JavaScript,还可以使用按钮甚至创建“假按钮”。但我不确定在我的情况下最好的方法是什么。
我尝试了在 Stackoverflow 上找到的解决方案:Youtube-example 这个有效,但在我的页面 TimeEdit 上没有我可以使用的 HTML 表单。相反,只有一个名为 searchButtons 的类,提交按钮和输入字段所在的位置。 这是我的示例代码:
WebClient webClient = new WebClient(BrowserVersion.CHROME);
webClient.getOptions().setCssEnabled(false);
webClient.getOptions().setJavaScriptEnabled(true);
webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
webClient.getOptions().setThrowExceptionOnScriptError(false);
webClient.getOptions().setUseInsecureSSL(true);
webClient.getCookieManager().setCookiesEnabled(true);
//Get the page
HtmlPage currentPage = webClient.getPage("https://se.timeedit.net/web/bth/db1/sched1/ri1Q7.html");
//Just for testing purpose
System.out.println(currentPage.getUrl());
// Get form where submit button is located
// But on this page there is no form, just a class called searchButtons
HtmlForm searchForm = (HtmlForm) currentPage.getElementById("ffsearchname");
// Get the input field.
HtmlTextInput searchInput = (HtmlTextInput) currentPage.getElementById("ffsearchname");
// Insert the search term.
searchInput.setText("DV1431");
// Workaround: create a 'fake' button and add it to the form.
HtmlButton submitButton = (HtmlButton) currentPage.createElement("button");
submitButton.setAttribute("type", "submit");
searchForm.appendChild(submitButton);
// Workaround: use the reference to the button to submit the form.
HtmlPage newPage = submitButton.click();
//Testing purpose
System.out.println(newPage.getUrl());
当提交按钮和输入字段不在表单中时,如何访问它?当我可以在输入字段中设置搜索词时,如何提交?
【问题讨论】:
标签: javascript html web-scraping htmlunit html-input