private static String get1025(String uname,String pwd) throws FailingHttpStatusCodeException, MalformedURLException, IOException, InterruptedException {
// 模拟一个浏览器
WebClient webClient = new WebClient(BrowserVersion.CHROME);
// 设置webClient的相关参数
webClient.setCssErrorHandler(new SilentCssErrorHandler());
//设置ajax
webClient.setAjaxController(new NicelyResynchronizingAjaxController());
//设置支持js
webClient.getOptions().setJavaScriptEnabled(true);
//CSS渲染禁止
webClient.getOptions().setCssEnabled(false);
//超时时间
webClient.getOptions().setTimeout(50000);
//设置js抛出异常:false
webClient.getOptions().setThrowExceptionOnScriptError(false);
//允许重定向
webClient.getOptions().setRedirectEnabled(true);
//允许cookie
webClient.getCookieManager().setCookiesEnabled(true);
// 模拟浏览器打开一个目标网址
HtmlPage page = webClient.getPage(TARGET_URL);
/**等待js加载完全,CSDN这点 特别坑,js加载时间超长!!!!!!! 后人切记不要用CSDN模拟登陆!!!!!!!**/
webClient.waitForBackgroundJavaScript(10000*3);
// 根据form的名字获取页面表单,也可以通过索引来获取:page.getForms().get(0)
// HtmlForm form = page.getForms().get(0);
//HtmlTextInput username = (HtmlTextInput) page.getInputByName("username");
HtmlTextInput username = (HtmlTextInput)page.getElementsById("username").get(0);
// System.out.println();
HtmlPasswordInput password = (HtmlPasswordInput) page.getElementsById("password").get(0);
username.setValueAttribute(uname); //用户名
password.setValueAttribute(pwd); //密码
HtmlButton button = (HtmlButton) page.getElementsById("login").get(0);
// ScriptResult result = page.executeJavaScript("javascript:document.getElementsByClassName('logging')[0].click()");
// HtmlPage retPage = (HtmlPage) result.getNewPage();
HtmlPage retPage = button.click();
// 等待JS驱动dom完成获得还原后的网页
webClient.waitForBackgroundJavaScript(1000);
//输出跳转网页的地址
//System.out.println("跳转网址"+retPage.getUrl().toString());
//输出跳转网页的内容
//System.out.println(retPage.asXml());
//获取cookie
Set<Cookie> cookies = webClient.getCookieManager().getCookies();
Map<String, String> responseCookies = new HashMap<String, String>();
for (Cookie c : cookies) {
responseCookies.put(c.getName(), c.getValue());
System.out.print(c.getName()+":"+c.getValue());
}
//HtmlForm form = page.getForms().get(4);
HtmlPage page2 = webClient.getPage(AFTERURL);
//System.out.println(page2.getUrl().toString());
//HtmlForm form =
// HtmlTextInput xz = (HtmlTextInput) page2.getElementById("interest");
//xz.setValueAttribute("1025");
HtmlSelect select = page2.getElementByName("interest");
select.getOption(1);
// HtmlButton button2 = (HtmlButton)page.getAnchorByText("go_time();");
// HtmlPage lastPage = button2.click();
webClient.waitForBackgroundJavaScript(1000);
//System.out.println(retPage.getUrl().toString());
// System.out.println(page2.asXml());
String order ="用户名为:"+uname+"; 订单数为:"+patternOrder(page2.asXml(), "1025\\s*</td>\\s*<td>\\s*(\\d*)");
Thread.sleep(3000);
webClient.close();
return order;
}
HTMLUnit demo
最新推荐文章于 2022-11-16 18:52:20 发布