浅谈HtmlUnit的使用

时间:2022-07-08 14:40:52

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

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

三、访问指定页面

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

 import java.io.IOException;
import java.net.MalformedURLException;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage; public class Main { public static void main(String[] args) throws FailingHttpStatusCodeException, MalformedURLException, IOException {
// TODO Auto-generated method stub
final WebClient mWebClient = new WebClient();
final HtmlPage mHtmlPage = mWebClient.getPage("http://www.baidu.com");
System.out.println(mHtmlPage.asText());
mWebClient.closeAllWindows();
} }

运行结果:

 二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.javascript.StrictErrorReporter runtimeError
严重: 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]
二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.javascript.StrictErrorReporter runtimeError
严重: 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]
二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.javascript.StrictErrorReporter runtimeError
严重: 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]
二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
警告: 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>, "-".)
二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
警告: CSS error: 'http://www.baidu.com/' [1:143] Error in style rule. (Invalid token "*". Was expecting one of: <EOF>, <S>, <IDENT>, "}", ";".)
二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler warning
警告: CSS warning: 'http://www.baidu.com/' [1:143] Ignoring the following declarations in this rule.
二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
警告: 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>, "-".)
二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
警告: CSS error: 'http://www.baidu.com/' [2:204] Error in declaration. (Invalid token "normal". Was expecting one of: <S>, ":".)
二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
警告: CSS error: 'http://www.baidu.com/' [2:970] Error in style rule. (Invalid token "*". Was expecting one of: <EOF>, <S>, <IDENT>, "}", ";".)
二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler warning
警告: CSS warning: 'http://www.baidu.com/' [2:970] Ignoring the following declarations in this rule.
二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
警告: CSS error: 'http://www.baidu.com/' [4:856] Error in style rule. (Invalid token "*". Was expecting one of: <EOF>, <S>, <IDENT>, "}", ";".)
二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler warning
警告: CSS warning: 'http://www.baidu.com/' [4:856] Ignoring the following declarations in this rule.
二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
警告: CSS error: 'http://www.baidu.com/' [4:1016] Error in style rule. (Invalid token "*". Was expecting one of: <EOF>, <S>, <IDENT>, "}", ";".)
二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler warning
警告: CSS warning: 'http://www.baidu.com/' [4:1016] Ignoring the following declarations in this rule.
二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
警告: CSS error: 'http://www.baidu.com/' [5:68] Error in style rule. (Invalid token "*". Was expecting one of: <EOF>, <S>, <IDENT>, "}", ";".)
二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler warning
警告: CSS warning: 'http://www.baidu.com/' [5:68] Ignoring the following declarations in this rule.
二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
警告: CSS error: 'http://www.baidu.com/' [6:751] Error in style rule. (Invalid token "*". Was expecting one of: <EOF>, <S>, <IDENT>, "}", ";".)
二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler warning
警告: CSS warning: 'http://www.baidu.com/' [6:751] Ignoring the following declarations in this rule.
二月 03, 2015 11:46:02 上午 com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error
警告: CSS error: 'http://www.baidu.com/' [8:127] Error in expression; ':' found after identifier "progid".
二月 03, 2015 11:46:03 上午 com.gargoylesoftware.htmlunit.IncorrectnessListenerImpl notify
警告: Obsolete content type encountered: 'text/javascript'.
二月 03, 2015 11:46:03 上午 com.gargoylesoftware.htmlunit.IncorrectnessListenerImpl notify
警告: Obsolete content type encountered: 'text/javascript'.
百度一下,你就知道
百度一下
新闻hao123地图视频贴吧登录设置更多产品
把百度设为主页关于百度About Baidu
©2015 Baidu 使用百度前必读 京ICP证030173号

运行结果

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

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

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

 import java.io.IOException;
import java.net.MalformedURLException;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage; public class Main { public static void main(String[] args) throws FailingHttpStatusCodeException, MalformedURLException, IOException {
// TODO Auto-generated method stub
final WebClient mWebClient = new WebClient();
mWebClient.getOptions().setCssEnabled(false);
mWebClient.getOptions().setJavaScriptEnabled(false);
final HtmlPage mHtmlPage = mWebClient.getPage("http://www.baidu.com");
System.out.println(mHtmlPage.asText());
mWebClient.closeAllWindows();
} }
 百度一下,你就知道
搜索设置 | 登录
新 闻 网 页 贴 吧 知 道 MP3 图 片 视 频 地 图
百度一下
输入法
手写
拼音
关闭
空间 百科 hao123 | 更多>>
把百度设为主页
加入百度推广 | 搜索风云榜 | 关于百度 | About Baidu
©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方法获取

 import java.io.IOException;
import java.net.MalformedURLException; import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlDivision;
import com.gargoylesoftware.htmlunit.html.HtmlPage; public class Main { public static void main(String[] args) throws FailingHttpStatusCodeException, MalformedURLException, IOException {
// TODO Auto-generated method stub
final WebClient mWebClient = new WebClient(BrowserVersion.CHROME);
mWebClient.getOptions().setCssEnabled(false);
mWebClient.getOptions().setJavaScriptEnabled(false);
final HtmlPage mHtmlPage = mWebClient.getPage("http://www.yanyulin.info/");
//从[烟雨林博客]上获取标签hed的内容
HtmlDivision mdiv = (HtmlDivision)mHtmlPage.getElementById("hed");
System.out.println(mdiv.asText());
mWebClient.closeAllWindows();
} }

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

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

运行结果:

 <div id="hed">
<div class="top_part">
<div style="float:left;">
<a href="http://www.yanyulin.info">
<img src="http://www.yanyulin.info/theme/images/logo.png" alt="烟雨林-关注程序员的IT科技博客" title="烟雨林-关注程序员的IT科技博客" width="127px" height="29px"/>
</a>
</div>
<div align="right" style="padding: 5px 0 0 0px;">
<div class="side_search">
<form action="http://zhannei.baidu.com/cse/search" method="get" target="_blank" class="bdcs-search-form" id="bdcs-search-form">
<input type="hidden" name="s" value="36283161565572170"/>
<input type="hidden" name="entry" value="1"/>
<input type="text" name="q" class="search_input" id="bdcs-search-form-input" placeholder="找找看"/>
<input type="submit" class="search_btn" id="bdcs-search-form-submit" value="找找看"/>
</form>
</div>
<div id="google_search" class="side_search" style="margin-top:4px">
<form method="get" action="http://www.google.com.hk/search" target="_blank">
<input type="text" name="q" class="search_input" placeholder="Google一下"/>
<input type="submit" value="Google" name="btnG" id="btnG" class="search_btn" title="Google"/>
<input type="hidden" name="ie" value="UTF-8"/>
<input type="hidden" name="oe" value="UTF-8"/>
<input type="hidden" name="hl" value="zh-CN"/>
<input type="hidden" name="domains" value="www.yanyulin.info"/>
<input type="hidden" name="sitesearch" value="www.yanyulin.info"/>
</form>
</div>
</div>
</div>
</div>

运行结果

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

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

  4、模拟表单的提交

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