概述
无意中接触到Jsoup(中文社区),提供一套简便方便的API抓取HTML页面,十分方便,其提供的API对HTML的解析也有一种js的既视感
使用
Jsoup的connection本质是对HttpURLConnection的封装,一些参数设置也是如出一辙.不过HttpURLConnection实在是有点挫(习惯用httpclient),但是其HTML解析用着还蛮爽.
//获取连接
Connection connect = Jsoup.connect("https://www.baidu.com");
//设置参数
// connect.data("","")//查询参数
// .cookie("", "")//cookie
// .header("", "")//header
// .ignoreContentType(true)
// .ignoreHttpErrors(true)
// .proxy("host", 80)//代理
// .userAgent("Mozilla")//userAgent--HttpURLConnection经常设置此,不然容易出400之类错误
// .timeout(1000)//超时
// .method(Method.GET)//设置方法,一般与excute使用,get,post有专门的api
;
//执行
/* Response execute = connect.execute();
String body = execute.body();*/
//直接抓取获取页面
Document doc = connect.get();
// Document doc = connect.post();
// Document doc = Jsoup.parse("c://1.html");//静态抓取
String html = doc.html();
//解析Document
/* Element content = doc.getElementById("content");
Elements links = content.getElementsByTag("a");
for (Element link : links) {
String linkHref = link.attr("href");
String linkText = link.text();
}*/
//选择器
/* File input = new File("/tmp/input.html");
Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");
Elements links = doc.select("a[href]"); //带有href属性的a元素
Elements pngs = doc.select("img[src$=.png]");
//扩展名为.png的图片
Element masthead = doc.select("div.masthead").first();
//class等于masthead的div标签
Elements resultLinks = doc.select("h3.r > a"); //在h3元素之后的a元素
*/
//解析Element
/*
Element link = doc.select("a").first();//查找第一个a元素
String text = doc.body().text(); // "An example link"//取得字符串中的文本
String linkHref = link.attr("href"); // "http://example.com/"//取得链接地址
String linkText = link.text(); // "example""//取得链接地址中的文本
String linkOuterH = link.outerHtml();
// "<a href="http://example.com"><b>example</b></a>"
String linkInnerH = link.html(); // "<b>example</b>"//取得链接内的html内容
*/