| 以文本方式查看主题 - 课外天地 李树青 (http://www.njcie.com/bbs/index.asp) -- 信息检索原理课件 (http://www.njcie.com/bbs/list.asp?boardid=16) ---- [转帖]HtmlUnit-网页爬虫进阶篇 (http://www.njcie.com/bbs/dispbbs.asp?boardid=16&id=1624) |
| -- 作者:admin -- 发布时间:2016/1/14 7:41:25 -- [转帖]HtmlUnit-网页爬虫进阶篇 之前,亦枫写过一篇关于使用 Jsoup 抓取网页内容的文章:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>main.html</title>
<meta http-equiv="keywords" c>
<meta http-equiv="description" c>
<meta http-equiv="content-type" c>
<style type="text/css">
a {
line-height: 30px;
margin: 20px;
}
</style>
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
<script type="text/javascript">
var datas = [ {
href : "http://www.jianshu.com/p/8d8edf25850d",
title : "推荐一款编程字体,让代码看着更美"
}, {
href : "http://www.jianshu.com/p/153d9f31288d",
title : "Android 利用Camera实现中轴3D卡牌翻转效果"
}, {
href : "http://www.jianshu.com/p/d6fb0c9c9c26",
title : "【Eclipse】挖掘专属最有用的快捷键组合"
}, {
href : "http://www.jianshu.com/p/72d69b49d135",
title : "【IIS】Windows下利用IIS建立网站并实现局域网共享"
} ];
window.onload = function() {
var infos = document.getElementById("infos");
for( var i = 0 ; i < datas.length ; i++)
{
var a = document.createElement("a");
a.href = datas[i].href ;
a.innerText = datas[i].title;
infos.appendChild(a);
infos.appendChild(document.createElement("br"))
}
}
</script>
</head>
<body>
<div class="text" style=" text-align:center;">HtmlUnit 测试网页内容!</div>
<br>
<div id="infos"
style="width: 60%; border: 1px solid green; border-radius: 10px; margin: 0 auto;">
</div>
</body>
</html>
通过IIS发布本地网站(参考亦枫之前写的文章:
import java.io.IOException;
import java.net.MalformedURLException;
import java.text.ParseException;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.DomNodeList;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
/**
* @author 亦枫
* @created_time 2016年1月12日
* @file_user_todo Java测试类
* @blog http://www.jianshu.com/users/1c40186e3248/latest_articles
*/
public class JavaTest {
/**
* 入口函数
* @param args
* @throws ParseException
*/
public static void main(String[] args) throws ParseException {
try {
WebClient webClient = new WebClient(BrowserVersion.CHROME);
HtmlPage htmlPage = (HtmlPage) webClient.getPage("http://localhost/test.html");
DomNodeList domNodeList = htmlPage.getElementsByTagName("a");
for (int i = 0; i < domNodeList.size(); i++) {
DomElement domElement = (DomElement) domNodeList.get(i);
System.out.println(domElement.asText());
}
webClient.close();
} catch (FailingHttpStatusCodeException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行之后,在控制台打印的结果:
|