---
title: "使用HtmlUnit抓取百度搜索结果"
author: "wander754085"
date: "2012-08-21T20:21:00Z"
tags: ["网页分析", "网页抓取"]
categories: ["开源软件"]
slug: "htmlunit"
draft: false
lastmod: "2012-08-26T23:16:32Z"
id: 1649968
url: "https://wander754085.iteye.com/blog/1649968"
---

htmlunit 是一款开源的java 页面分析工具，读取页面后，可以有效的使用htmlunit分析页面上的内容。项目可以模拟浏览器运行，被誉为java浏览器的开源实现。这个没有界面的浏览器，运行速度也是非常迅速的。相关文件下载地址：[http://sourceforge.net/projects/htmlunit/files/](http://sourceforge.net/projects/htmlunit/files/) （依赖的包略多![微笑](http://static.blog.csdn.net/xheditor/xheditor_emot/default/smile.gif)）

 

我的需求是使用百度的高级新闻搜索，抓取指定时间段的新闻，手动搜索的设置如图所示：

![](http://my.csdn.net/uploads/201208/21/1345551970_9209.jpg)

通过htmlunit可以方便地操作网页中的form和各类的input控件，如HtmlSubmitInput，HtmlTextInput，HtmlRadioButtonInput，HtmlHiddenInput等等，可以通过name和value查找对应的DOM结点。一开始遇到的问题是，即使正确地操作了radio Button，也不能得出正确的时间段内的结果，用chrome查看了Http header后发现，百度在form中隐藏了两个参数，参数名为bt和et，分别代表用户选中的那两个时间begin\_date和end\_date与1970-1-1之间的间隔时长的时间戳，因此还需要手动添加这两个参数，才能得出对应时间段的结果，代码如下：

```
final WebClient webclient = new WebClient();
		final HtmlPage htmlpage = webclient
				.getPage("http://news.baidu.com/advanced_news.html");
		webclient.setCssEnabled(false);
		webclient.setJavaScriptEnabled(false);
		// System.out.println(htmlpage.getTitleText());
		final HtmlForm form = htmlpage.getFormByName("f");
		final HtmlSubmitInput button = form.getInputByValue("百度一下");
		final HtmlTextInput textField = form.getInputByName("q1");
		textField.setValueAttribute(word);
		final List<HtmlRadioButtonInput> radioButtons = form
				.getRadioButtonsByName("s");
		radioButtons.get(0).setChecked(false);
		radioButtons.get(1).setChecked(true);// 选中限定时间段的radion button
		final List<HtmlRadioButtonInput> titleButtons = form
				.getRadioButtonsByName("tn");
		titleButtons.get(0).setChecked(false);
		titleButtons.get(1).setChecked(true); //选中“仅在新闻的标题中”的radion button
		HtmlHiddenInput bt = form.getInputByName("bt");
		bt.setValueAttribute("1167580800"); //2007-1-1的时间戳
		HtmlHiddenInput et = form.getInputByName("et");
		et.setValueAttribute("1199116799"); //2007-12-31的时间戳
		final HtmlPage page2 = button.click();
		String result = page2.asText();
		Pattern pattern = Pattern.compile("找到相关新闻 约(.*) 篇");
		Matcher matcher = pattern.matcher(result);
		webclient.closeAllWindows();
                if (matcher.find())
			return matcher.group(1)；
```