htmlunit 网贷之家模拟登录

    网贷之家模拟登录:

	public void wdzjLogin() throws Exception {
		try{
	       //创建一个webclient  
            WebClient webClient = new WebClient(BrowserVersion.CHROME);   
              
            //参数设置  
            // 1 启动JS  
            webClient.getOptions().setJavaScriptEnabled(true);  
            // 2 禁用Css,可避免自动二次请求CSS进行渲染  
            webClient.getOptions().setCssEnabled(false);  
            //3 启动客户端重定向  
            webClient.getOptions().setRedirectEnabled(true);  
            // 4 运行错误时,是否抛出异常  
            webClient.getOptions().setThrowExceptionOnScriptError(false);  
            // 5 设置超时  
            webClient.getOptions().setTimeout(50000);  
            //6 设置忽略证书  
            //webClient.getOptions().setUseInsecureSSL(true);  
            //7 设置Ajax  
            //webClient.setAjaxController(new NicelyResynchronizingAjaxController());  
            //8设置cookie  
            webClient.getCookieManager().setCookiesEnabled(true);  
              
            //获取页面  
            HtmlPage page = webClient.getPage("https://passport.wdzj.com/user/login");    
            // 根据form的名字获取页面表单,也可以通过索引来获取:page.getForms().get(0)     
            HtmlForm form = page.getForms().get(0);    
            HtmlTextInput username = (HtmlTextInput) form.getInputByName("username");
            HtmlPasswordInput password = (HtmlPasswordInput) form.getInputByName("password");  
            username.setValueAttribute("XXXXX");  //  输入注册账号
            password.setValueAttribute("XXXXX");  //  输入注册密码
            HtmlButtonInput button = (HtmlButtonInput)page.getHtmlElementById("login_submit");     
            HtmlPage retPage = (HtmlPage) button.click();  
            // 等待JS驱动dom完成获得还原后的网页  
            webClient.waitForBackgroundJavaScript(10000);  
            //输出网页内容  

            //获取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());  
            }  
             
            retPage = webClient.getPage("http://shuju.wdzj.com/problem-1.html");
	        HtmlDivision tabDiv = retPage.getHtmlElementById("tableTmpl");
	       
	        HtmlTable htmlTab = (HtmlTable) tabDiv.getChildElements().iterator().next();

	        for(HtmlTableRow row: htmlTab.getRows()){ 		// 遍历所有行
                for(HtmlTableCell cell:row.getCells()){  	        // 遍历所有列
                    System.out.print(cell.asText()+"|");
                }
                System.out.println();
            }
            //关闭webclient  
            webClient.close();   
	        
	    }catch(Exception e){
	    	e.printStackTrace();
	    }
	}

猜你喜欢

转载自blog.csdn.net/caowenyi88/article/details/80264426