想要使用 HtmlUnit 选择不在表单内的选项。然后我当然需要检索结果页面。这是我尝试过的:
public String getNewPage() throws Exception {
try (final WebClient webClient = new WebClient()) {
webClient.getOptions().setThrowExceptionOnScriptError(false);
webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
webClient.getOptions().setPopupBlockerEnabled(true);
webClient.getOptions().setJavaScriptEnabled(true);
final HtmlPage page = webClient.getPage(URL);
HtmlOption option1 = (HtmlOption) page.getElementById("1");
option1.removeAttribute("selected");
HtmlOption option5 = (HtmlOption) page.getElementById("5");
option5.setSelected(true);
// Some code missing here........
return newHtmlString;
}
单击选项时页面会自动更新。选择正确选项后如何获取新页面?
最佳答案
我所做的几乎是正确的,但缺少以下内容:
page.refresh();
return page.asXml();
然后我遇到了另一个将复选框标记为已选中的问题。这是对我有用的:
HtmlCheckBoxInput checkbox = (HtmlCheckBoxInput) page.getElementById("cb4");
checkbox.setAttribute("checked", "checked");
checkbox.fireEvent(Event.TYPE_CHANGE);
page.refresh();
System.out.println(page.asXml());
关于java - HtmlUnit 选择不在表单中的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40008348/