使用htmlunit模擬登錄的時候 ,首先穿創建了一個webclient 用webclient請求登錄頁面,同事請求解析驗證碼,驗證碼解析正確,然後開始登錄系統,一直提示驗證碼錯誤。
WebClient webClient = new WebClient(BrowserVersion.INTERNET_EXPLORER_11);
webClient.getOptions().setJavaScriptEnabled(true);
webClient.getOptions().setCssEnabled(false);
webClient.setAjaxController(new NicelyResynchronizingAjaxController());
webClient.getOptions().setThrowExceptionOnScriptError(false);
webClient .getOptions().setUseInsecureSSL(true);
WebWindow webWindow = webClient.getCurrentWindow();
WebRequest request1 = new WebRequest(new URL("http://rd2.zhaopin.com/s/loginmgr/login.asp"));
HtmlPage htmlPage = webClient.getPage(webWindow,request1);
String name = htmlPage.getWebClient().getWebWindows().get(0).getName();
System.out.println(name);
//第三步 獲取界面元素
HtmlInput userName = htmlPage.getHtmlElementById("LoginName");
HtmlInput password = htmlPage.getHtmlElementById("Password");
HtmlInput checkCode = htmlPage.getHtmlElementById("CheckCode");
HtmlInput btn = htmlPage.getHtmlElementById("login");
WebRequest request = new WebRequest(new URL("https://passport.zhaopin.com/checkcode/imgrd"));
UnexpectedPage imagePage = webClient.getPage(webWindow,request);
InputStream in = imagePage.getWebResponse().getContentAsStream();
File storeFile = new File("D:/zlzp.png");
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(storeFile));
byte[] buf = new byte[2048];
int length = in.read(buf);
while (length != -1) {
output.write(buf, 0, length);
length = in.read(buf);
}
in.close();
output.close();
String valCode = new OCR().recognizeText(new File("D:\\zlzp.png"), "png");
System.out.println(valCode);
userName.setAttribute("value", "");
password.setAttribute("value", "");
checkCode.setAttribute("value", valCode);
HtmlPage page2 = btn.click();
System.out.println("\n\n\n");
System.out.println(page2.asText());
用fiddler看下,是不是你請求了多次頁面,也就是你識別的驗證碼不是最終的,或者你沒有帶上cookie