HtmlUnit是一个很棒的Java库,允许您以编程方式填写和提交Web表单.我目前正在维护一个用ASP编写的旧系统,而不是按照我的要求每月手动填写这一个Web表单,我试图找到一种方法来自动完成整个任务,因为我保持忘了它.它是一种用于检索一个月内收集的数据的表单.这是我到目前为止编码的内容:
WebClient client = new WebClient();
HtmlPage page = client.getPage("http://urlOfTheWebsite.com/search.aspx");
HtmlForm form = page.getFormByName("aspnetForm");
HtmlSelect frMonth = form.getSelectByName("ctl00$cphContent$ddlStartMonth");
HtmlSelect frDay = form.getSelectByName("ctl00$cphContent$ddlStartDay");
HtmlSelect frYear = form.getSelectByName("ctl00$cphContent$ddlStartYear");
HtmlSelect toMonth = form.getSelectByName("ctl00$cphContent$ddlEndMonth");
HtmlSelect toDay = form.getSelectByName("ctl00$cphContent$ddlEndDay");
HtmlSelect toYear = form.getSelectByName("ctl00$cphContent$ddlEndYear");
HtmlCheckBoxInput games = form.getInputByName("ctl00$cphContent$chkListLottoGame$0");
HtmlSubmitInput submit = form.getInputByName("ctl00$cphContent$btnSearch");
frMonth.setSelectedAttribute("1", true);
frDay.setSelectedAttribute("1", true);
frYear.setSelectedAttribute("2012", true);
toMonth.setSelectedAttribute("1", true);
toDay.setSelectedAttribute("31", true);
toYear.setSelectedAttribute("2012", true);
games.setChecked(true);
submit.click();
Run Code Online (Sandbox Code Playgroud)
之后click(),我应该等待同一个网页完成重新加载,因为某处有一个表格显示我的搜索结果.然后,当页面加载完成后,我需要将其作为HTML文件下载(非常类似于您最喜爱的浏览器中的"保存页面..."),因为我将清除数据以计算总数,而且我已经使用Jsoup库完成了.
我的问题是:1.如何以编程方式等待网页在HtmlUnit中完成加载?2.如何以编程方式将生成的网页下载为HTML文件?
我已经查看了HtmlUnit文档,但找不到能满足我需求的类.
尝试使用以下设置:
webClient.waitForBackgroundJavaScript() or
webClient.waitForBackgroundJavaScriptStartingBefore()
Run Code Online (Sandbox Code Playgroud)
我想你也需要提一下浏览器.默认它是使用IE.You将从这里获得更多信息. HTMLUnit不等待Javascript
如何以编程方式将生成的网页下载为 HTML 文件
尝试asXml()。就像是:
page = submit.click();
String htmlContent = page.asXml();
File htmlFile = new File("C:/index.html");
PrintWriter pw = new PrintWriter(htmlFile, true);
pw.print(htmlContent);
pw.close();
Run Code Online (Sandbox Code Playgroud)