zoukankan      html  css  js  c++  java
  • 浅谈HtmlUnit的使用

    htmlunit 是一款开源的java 页面分析工具,读取页面后,可以有效的使用htmlunit分析页面上的内容。项目可以模拟浏览器运行,被誉为java浏览器的开源实现。这个没有界面的浏览器,运行速度也是非常迅速的。

    二、下载地址:http://sourceforge.net/projects/htmlunit/?source=directory 

    三、访问指定页面

      网络爬虫第一个要面临的问题,就是如何抓取网页,抓取其实很容易,没你想的那么复杂,一个开源HtmlUnit包,4行主要代码就OK啦!

     1 import java.io.IOException;
     2 import java.net.MalformedURLException;
     3 import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
     4 import com.gargoylesoftware.htmlunit.WebClient;
     5 import com.gargoylesoftware.htmlunit.html.HtmlPage;
     6 
     7 public class Main {
     8 
     9     public static void main(String[] args) throws FailingHttpStatusCodeException, MalformedURLException, IOException {
    10         // TODO Auto-generated method stub
    11         final WebClient mWebClient = new WebClient();
    12         final HtmlPage mHtmlPage = mWebClient.getPage("http://www.baidu.com");
    13         System.out.println(mHtmlPage.asText());
    14         mWebClient.closeAllWindows();
    15     }
    16 
    17 }

    运行结果:

     1 二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.javascript.StrictErrorReporter runtimeError
     2 严重: runtimeError: message=[An invalid or illegal selector was specified (selector: ':checked' error: Invalid selector: *:checked).] sourceName=[http://s1.bdstatic.com/r/www/cache/static/jquery/jquery-1.10.2.min_f2fb5194.js] line=[14] lineSource=[null] lineOffset=[0]
     3 二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.javascript.StrictErrorReporter runtimeError
     4 严重: runtimeError: message=[An invalid or illegal selector was specified (selector: ':enabled' error: Invalid selector: *:enabled).] sourceName=[http://s1.bdstatic.com/r/www/cache/static/jquery/jquery-1.10.2.min_f2fb5194.js] line=[14] lineSource=[null] lineOffset=[0]
     5 二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.javascript.StrictErrorReporter runtimeError
     6 严重: runtimeError: message=[The data necessary to complete this operation is not yet available.] sourceName=[http://s1.bdstatic.com/r/www/cache/static/jquery/jquery-1.10.2.min_f2fb5194.js] line=[10] lineSource=[null] lineOffset=[0]
     7 二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
     8 警告: CSS error: 'http://www.baidu.com/' [1:81] Error in expression. (Invalid token ";". Was expecting one of: <S>, <NUMBER>, "inherit", <IDENT>, <STRING>, <PLUS>, <HASH>, <EMS>, <EXS>, <LENGTH_PX>, <LENGTH_CM>, <LENGTH_MM>, <LENGTH_IN>, <LENGTH_PT>, <LENGTH_PC>, <ANGLE_DEG>, <ANGLE_RAD>, <ANGLE_GRAD>, <TIME_MS>, <TIME_S>, <FREQ_HZ>, <FREQ_KHZ>, <PERCENTAGE>, <DIMENSION>, <URI>, <FUNCTION>, "-".)
     9 二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
    10 警告: CSS error: 'http://www.baidu.com/' [1:143] Error in style rule. (Invalid token "*". Was expecting one of: <EOF>, <S>, <IDENT>, "}", ";".)
    11 二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler warning
    12 警告: CSS warning: 'http://www.baidu.com/' [1:143] Ignoring the following declarations in this rule.
    13 二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
    14 警告: CSS error: 'http://www.baidu.com/' [1:339] Error in expression. (Invalid token ";". Was expecting one of: <S>, <NUMBER>, "inherit", <IDENT>, <STRING>, <PLUS>, <HASH>, <EMS>, <EXS>, <LENGTH_PX>, <LENGTH_CM>, <LENGTH_MM>, <LENGTH_IN>, <LENGTH_PT>, <LENGTH_PC>, <ANGLE_DEG>, <ANGLE_RAD>, <ANGLE_GRAD>, <TIME_MS>, <TIME_S>, <FREQ_HZ>, <FREQ_KHZ>, <PERCENTAGE>, <DIMENSION>, <URI>, <FUNCTION>, "-".)
    15 二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
    16 警告: CSS error: 'http://www.baidu.com/' [2:204] Error in declaration. (Invalid token "normal". Was expecting one of: <S>, ":".)
    17 二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
    18 警告: CSS error: 'http://www.baidu.com/' [2:970] Error in style rule. (Invalid token "*". Was expecting one of: <EOF>, <S>, <IDENT>, "}", ";".)
    19 二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler warning
    20 警告: CSS warning: 'http://www.baidu.com/' [2:970] Ignoring the following declarations in this rule.
    21 二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
    22 警告: CSS error: 'http://www.baidu.com/' [4:856] Error in style rule. (Invalid token "*". Was expecting one of: <EOF>, <S>, <IDENT>, "}", ";".)
    23 二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler warning
    24 警告: CSS warning: 'http://www.baidu.com/' [4:856] Ignoring the following declarations in this rule.
    25 二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
    26 警告: CSS error: 'http://www.baidu.com/' [4:1016] Error in style rule. (Invalid token "*". Was expecting one of: <EOF>, <S>, <IDENT>, "}", ";".)
    27 二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler warning
    28 警告: CSS warning: 'http://www.baidu.com/' [4:1016] Ignoring the following declarations in this rule.
    29 二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
    30 警告: CSS error: 'http://www.baidu.com/' [5:68] Error in style rule. (Invalid token "*". Was expecting one of: <EOF>, <S>, <IDENT>, "}", ";".)
    31 二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler warning
    32 警告: CSS warning: 'http://www.baidu.com/' [5:68] Ignoring the following declarations in this rule.
    33 二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
    34 警告: CSS error: 'http://www.baidu.com/' [6:751] Error in style rule. (Invalid token "*". Was expecting one of: <EOF>, <S>, <IDENT>, "}", ";".)
    35 二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler warning
    36 警告: CSS warning: 'http://www.baidu.com/' [6:751] Ignoring the following declarations in this rule.
    37 二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
    38 警告: CSS error: 'http://www.baidu.com/' [8:127] Error in expression; ':' found after identifier "progid".
    39 二月 03, 2015 11:46:03 上午 com.gargoylesoftware.htmlunit.IncorrectnessListenerImpl notify
    40 警告: Obsolete content type encountered: 'text/javascript'.
    41 二月 03, 2015 11:46:03 上午 com.gargoylesoftware.htmlunit.IncorrectnessListenerImpl notify
    42 警告: Obsolete content type encountered: 'text/javascript'.
    43 百度一下,你就知道
    44 百度一下
    45 新闻hao123地图视频贴吧登录设置更多产品
    46 把百度设为主页关于百度About Baidu
    47 ©2015 Baidu 使用百度前必读 京ICP证030173号 
    运行结果

     在上面的程序运行的过程中,我们可以得到百度首页的所有内容,上面的代码在运行的过程中会出现很多的警告,出现这些警告的主要原因是由于以下两种原因:

    1、HtmlUnit对Javascript的支持不是很好
    2、HtmlUnit对CSS的支持不是很好

      明白了上面的两点后,将代码重新改写一下,该禁用的就禁用,同时禁用一些不必要的功能,也有利于提高程序的运行效率,再者说网络爬虫也不需要CSS的支持。

     1 import java.io.IOException;
     2 import java.net.MalformedURLException;
     3 import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
     4 import com.gargoylesoftware.htmlunit.WebClient;
     5 import com.gargoylesoftware.htmlunit.html.HtmlPage;
     6 
     7 public class Main {
     8 
     9     public static void main(String[] args) throws FailingHttpStatusCodeException, MalformedURLException, IOException {
    10         // TODO Auto-generated method stub
    11         final WebClient mWebClient = new WebClient();
    12         mWebClient.getOptions().setCssEnabled(false);
    13         mWebClient.getOptions().setJavaScriptEnabled(false);
    14         final HtmlPage mHtmlPage = mWebClient.getPage("http://www.baidu.com");
    15         System.out.println(mHtmlPage.asText());
    16         mWebClient.closeAllWindows();
    17     }
    18 
    19 }
     1 百度一下,你就知道
     2 搜索设置 | 登录
     3 新 闻 网 页 贴 吧 知 道 MP3 图 片 视 频 地 图
     4 百度一下
     5 输入法
     6 手写
     7 拼音
     8 关闭
     9 空间 百科 hao123 | 更多>>
    10 把百度设为主页
    11 加入百度推广 | 搜索风云榜 | 关于百度 | About Baidu
    12 ©2014 Baidu 使用百度前必读 京ICP证030173号
    运行结果

      HtmlUnit的使用: 简介:HtmlUnit说白了就是一个浏览器,这个浏览器是用Java写的无界面的浏览器,正因为其没有界面,因此执行的速度还是可以滴,HtmlUnit提供了一系列的API,这些API可以干的功能比较多,如表单的填充,表单的提交,模仿点击链接,由于内置了Rhinojs引擎,因此可以执行Javascript

      作用:web的自动化测试(最初的目的),浏览器,网络爬虫

      重要API的使用 在介绍API的使用之前要先明白的一个问题是,WebClient,WebWindow,Page三者之间的关系,所有的页面最终都是在一个WebWindow对象里面,WebClient在创建时会自动的创建一个WebWindow对象,当调用getPage时会将新页面加载到WebWindow里,你可以理解成WebClient就是IE内核,WebWindow就是呈现页面的浏览器窗口,三者之间的关系图如下图所示:

      1、模拟特定浏览器,也可以指定浏览器的相应版本(HtmlUnit最新版2.13现在可以模拟的浏览器有Chrome/FireFox/IE)

    //模拟chorme浏览器,其他浏览器请修改BrowserVersion.后面
    final WebClient mWebClient = new WebClient(BrowserVersion.CHROME);

      2、查找特定元素,通过get或者XPath可以从HtmlPage中获得特定的Html元素,如下例子
      方法一,通过get方法获取

     1 import java.io.IOException;
     2 import java.net.MalformedURLException;
     3 
     4 import com.gargoylesoftware.htmlunit.BrowserVersion;
     5 import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
     6 import com.gargoylesoftware.htmlunit.WebClient;
     7 import com.gargoylesoftware.htmlunit.html.HtmlDivision;
     8 import com.gargoylesoftware.htmlunit.html.HtmlPage;
     9 
    10 public class Main {
    11 
    12     public static void main(String[] args) throws FailingHttpStatusCodeException, MalformedURLException, IOException {
    13         // TODO Auto-generated method stub
    14         final WebClient mWebClient = new WebClient(BrowserVersion.CHROME);
    15         mWebClient.getOptions().setCssEnabled(false);
    16         mWebClient.getOptions().setJavaScriptEnabled(false);
    17         final HtmlPage mHtmlPage = mWebClient.getPage("http://www.yanyulin.info/");
    18         //从[烟雨林博客]上获取标签hed的内容
    19         HtmlDivision mdiv = (HtmlDivision)mHtmlPage.getElementById("hed");
    20         System.out.println(mdiv.asText());
    21         mWebClient.closeAllWindows();
    22     }
    23 
    24 }

      方法二,通过XPath获取,XPath通常用于无法通过Id搜索,或者需要更为复杂的搜索时,XPath的相关教程。

    1         // 同样可以打印出hed的内容,//div中//表示搜索整个文档中的div,并将这些div
    2         // 放入list中,然后获取第一个div
    3         HtmlDivision mdiv = (HtmlDivision) mHtmlPage.getByXPath("//div").get(0);
    4         System.out.println(mdiv.asXml());

    运行结果:

     1 <div id="hed">
     2   <div class="top_part">
     3     <div style="float:left;">
     4       <a href="http://www.yanyulin.info">
     5         <img src="http://www.yanyulin.info/theme/images/logo.png" alt="烟雨林-关注程序员的IT科技博客" title="烟雨林-关注程序员的IT科技博客" width="127px" height="29px"/>
     6       </a>
     7     </div>
     8     <div align="right" style="padding: 5px 0 0 0px;">
     9       <div class="side_search">
    10         <form action="http://zhannei.baidu.com/cse/search" method="get" target="_blank" class="bdcs-search-form" id="bdcs-search-form">
    11           <input type="hidden" name="s" value="36283161565572170"/>
    12           <input type="hidden" name="entry" value="1"/>
    13           <input type="text" name="q" class="search_input" id="bdcs-search-form-input" placeholder="找找看"/>
    14           <input type="submit" class="search_btn" id="bdcs-search-form-submit" value="找找看"/>
    15         </form>
    16       </div>
    17       <div id="google_search" class="side_search" style="margin-top:4px">
    18         <form method="get" action="http://www.google.com.hk/search" target="_blank">
    19           <input type="text" name="q" class="search_input" placeholder="Google一下"/>
    20           <input type="submit" value="Google" name="btnG" id="btnG" class="search_btn" title="Google"/>
    21           <input type="hidden" name="ie" value="UTF-8"/>
    22           <input type="hidden" name="oe" value="UTF-8"/>
    23           <input type="hidden" name="hl" value="zh-CN"/>
    24           <input type="hidden" name="domains" value="www.yanyulin.info"/>
    25           <input type="hidden" name="sitesearch" value="www.yanyulin.info"/>
    26         </form>
    27       </div>
    28     </div>
    29   </div>
    30 </div>
    运行结果

      3、代理服务器的配置,代理的配置很简单,只需要配置好地址,端口,用户名与密码即可。

    1         final WebClient mWebClient = new WebClient(BrowserVersion.CHROME,"http://127.0.0.1", 8080);
    2         final DefaultCredentialsProvider credentialsProvider = (DefaultCredentialsProvider) mWebClient.getCredentialsProvider();
    3         credentialsProvider.addCredentials("username", "password");

      4、模拟表单的提交

    ++++++++++++++++

     

     

     

  • 相关阅读:
    Linux实战教学笔记14:用户管理初级(上)
    上传文件到服务器指定位置 & 从服务器指定位置下载文件
    flume读取日志文件并存储到HDFS
    Kafka
    Eclipse获取工作空间跟运行空间
    Java开发webservice的几种方式
    获取.properties配置文件属性值
    数组合并
    字符串对象跟xml格式的转换
    文件压缩跟解压(本地&Linux服务器)
  • 原文地址:https://www.cnblogs.com/zhjsll/p/4269576.html
Copyright © 2011-2022 走看看