爬蟲技術之 htmlunit 使用入門

1 htmlunit簡介

 htmlunit是java實現的開源無界面瀏覽器,可以有效的加載動態頁面。

2 htmlunit的獲取

2.1 maven 構建

<dependency>
  <groupId>net.sourceforge.htmlunit</groupId>
  <artifactId>htmlunit</artifactId>
  <version>2.31</version>
</dependency>

2.2 官網下載

 下載地址

3 具體使用

3.1獲取頁面

  //獲取頁面
        WebClient webClient=new WebClient();
        //是否開啓js渲染
        webClient.getOptions().setJavaScriptEnabled(true);
        HtmlPage page=null;
        try {
            page=webClient.getPage("https://mp.csdn.net/");
            //等待頁面渲染完成
            Thread.sleep(3000);
            //控制檯打印出頁面
            System.out.println(page.asXml());
        } catch (Exception e) {
            e.printStackTrace();
        }


3.2 一些設置

       //是否開啓css渲染
        webClient.getOptions().setCssEnabled(false);
        //是否開啓js渲染
        webClient.getOptions().setJavaScriptEnabled(true);
        //是否允許所有人鏈接(解決https證書不信任問題)
        webClient.getOptions().setUseInsecureSSL(true);
        //js失敗是否拋出異常
        webClient.getOptions().setThrowExceptionOnScriptError(false);
        //是否啓用重定向
        webClient.getOptions().setRedirectEnabled(true);

3.3 執行頁面js

      //執行頁面js,並獲得結果,獲取頁面中變量_hmt的值
        ScriptResult t=page.executeJavaScript("_hmt ");
        System.out.println(t.getJavaScriptResult().toString());
3.4操作dom樹,並觸發相關事件

    

      //獲取元素 類似js語法的操作方式
        DomElement domElement= page.getElementById("feedlist_id");
        try {
            //觸發單擊事件,獲得新的頁面
          HtmlPage page1= domElement.click();
        } catch (IOException e) {
            e.printStackTrace();
        }

3.5與httpclient相互轉換

    在爬蟲使用時。可能涉及到這兩個工具的結合使用,其實轉換的核心就是cookie的轉換

  //創建httpclient的客戶端
        CookieStore cookieStore = new BasicCookieStore();
        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultCookieStore(cookieStore)
                .build();
        //獲取htmlunit cookie;
      Set<Cookie> htmlUnitCookies=  webClient.getCookieManager().getCookies();
      //將htmlunit cookie 轉換成htmlclient cookie
      for(Cookie cookie:htmlUnitCookies){
          cookieStore.addCookie(new BasicClientCookie(cookie.getName(),cookie.getValue()));
      }

      //獲取htmlclient cookie
        List<org.apache.http.cookie.Cookie> httpClientCookies= cookieStore.getCookies();
        //cookie 轉換
        for(org.apache.http.cookie.Cookie cookie:httpClientCookies){
            webClient.getCookieManager().addCookie(new Cookie(cookie.getDomain(),cookie.getName(),cookie.getValue()));
        }


 


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章