爬虫技术之 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()));
        }


 


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值