360SDN.COM

首页/Java/列表

java使用htmlunit爬虫模拟登陆(WebClient ,HtmlTextInput ,HtmlSubmitInput click

来源:  2017-08-30 17:12:19    评论:0点击:

来源:https://stackoverflow.com/questions/34314202/java-htmlunit-webclient-ssl-page

public static void main(String[] args)
        throws FailingHttpStatusCodeException, MalformedURLException,
        IOException {

        WebClient wc = initWebClient(null);

        HtmlPage page = wc.getPage(Constants.START_PAGE);

        HtmlTextInput userInput = (HtmlTextInput) page
            .getElementById(Constants.INPUT_USERNAME_ID);
        userInput.setText(Constants.USERNAME_VALUE);

        HtmlPasswordInput passwordInput = (HtmlPasswordInput) page
            .getElementById(Constants.INPUT_PASSWORD_ID);
        passwordInput.setText(Constants.PASSWORD_VALUE);

        // get submit button
        HtmlSubmitInput submitButton = (HtmlSubmitInput) page
            .getElementById(Constants.SUBMIT_BUTTON_ID);

        HtmlPage afterLoginPage = submitButton.click();

       Set<Cookie> cookies = wc.getCookieManager().getCookies();
     
       // for every thread I create new WebClient
       for(threads loop){
           WebClient wc2 = initWebClient(cookies);
       }
    }

    private static WebClient initWebClient(Set<Cookie> cookies) {
       WebClient wc = new WebClient(BrowserVersion.CHROME);
       wc.getCookieManager().setCookiesEnabled(true);
       wc.getOptions().setJavaScriptEnabled(false);
       wc.getOptions().setThrowExceptionOnScriptError(false);

       if (cookies != null) {
          Iterator<Cookie> i = cookies.iterator();
          while (i.hasNext()) {
              wc.getCookieManager().addCookie(i.next());
          }
        }

        return wc;
   }
为您推荐

友情链接 |九搜汽车网 |手机ok生活信息网|ok生活信息网|ok微生活
 Powered by www.360SDN.COM   京ICP备11022651号-4 © 2012-2016 版权