htmlunit模拟登录

 使用htmlunit登录的原因是前端有加密控件,所以输入密码的时候使用的是键盘输入

WebClient webClient = new WebClient(BrowserVersion.FIREFOX);
webClient.getOptions().setCssEnabled(false);//关闭css
webClient.getOptions().setJavaScriptEnabled(true);//开启js
webClient.getOptions().setRedirectEnabled(true);//重定向
webClient.getOptions().setThrowExceptionOnScriptError(false);//关闭js报错
webClient.getOptions().setTimeout(50000);//超时时间
webClient.getCookieManager().setCookiesEnabled(true);//允许cookie
webClient.setAjaxController(new NicelyResynchronizingAjaxController());//设置支持AJAX
HtmlPage page = webClient.getPage("url");
HtmlForm loginForm = page.getFormByName("loginForm");
//输入账号
HtmlInput userName = loginForm.getInputByName("userName");
aName.setValueAttribute("18888888888");
//点击控件后键盘输入密码
HtmlElement pwd = page.getHtmlElementById("pwd");
pwd.click();
pwd.type((char) KeyboardEvent.DOM_VK_6);
pwd.type((char) KeyboardEvent.DOM_VK_6);
pwd.type((char) KeyboardEvent.DOM_VK_6);
//此处获取cookie,原本打算拿到cookie后发请求打码的,但是总是验证码出错。只能保存到本地
CookieManager cookieManager = webClient.getCookieManager();
//Map<String, String> headers = new HashMap<>();
Cookie cookie = cookieManager.getCookie("JSESSIONID");
COOKIE =cookie.toString();
//headers.put("Cookie", cookie.toString());
//Map<String, String> dama = xxx.xxx(HTTPUtils.xxx("url", headers, ""));
//HtmlInput captch = loginForm.getInputByName("captch");
//captch.setValueAttribute(dama.get("captch"));
//输入验证码,验证码保存在本地
File file = File.createTempFile(DateUtils.format(new Date(),"yyyyMMdd_HHmmss") + new Random().nextInt(100), ".png");
HtmlImage img = (HtmlImage) page.getElementById("img");
img.saveAs(file);
Map<String, String> xxx = xxx.xxx(FileUtils.readFileToByteArray(file));
HtmlInput code = loginForm.getInputByName("code");
code.setValueAttribute(xxx.get("value"));
System.err.println(file.delete());
//选择checkBox
List<HtmlRadioButtonInput> radios = loginForm.getRadioButtonsByName("radio");
for (HtmlRadioButtonInput r : radios){
    if (r.getDefaultValue().equals("xxx")){
    r.click();
    break;
}
//点击登录  button没有name属性
HtmlElement submitButton = page.getHtmlElementById("submitButton");
submitButton.click();
//等待JS驱动dom完成获得还原后的网页
//webClient.waitForBackgroundJavaScript(30000);
//无法自动跳转,主动去跳转页面查看是否登录成功(我这里怎么搞都没法自动跳转,就这么处理了)
HtmlPage page1 = webClient.getPage("url1");
webClient.close();
if (page1.getUrl().equals(page.getUrl())){
    LogUtils.error("未登录成功");
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值