因項(xiàng)目需要從某個(gè)網(wǎng)站爬取一點(diǎn)數(shù)據(jù),故我將爬取記錄如下,以后說(shuō)不定還能用得到呢,廢話少說(shuō),進(jìn)入正題:
HttpClient 是 Apache Jakarta Common 下的子項(xiàng)目,可以用來(lái)提供高效的、最新的、功能豐富的支持 HTTP 協(xié)議的客戶端編程工具包,并且它支持 HTTP 協(xié)議最新的版本和建議。本文首先介紹 HTTPClient,然后根據(jù)作者實(shí)際工作經(jīng)驗(yàn)給出了一些常見問(wèn)題的解決方法。
HttpClient 主頁(yè):http://hc.apache.org/httpcomponents-client-dev/index.html
jsoup是一個(gè)Java HTML Parser。能夠從URL、文件或字符串解析HTML。利用DOM遍歷或CSS選擇器查找和抽取數(shù)據(jù)。能夠操作HTML元素,屬性和文本。能夠依據(jù)一個(gè)白名單過(guò)濾用戶提交的內(nèi)容。
jsoup主頁(yè):http://jsoup.org/
具體的我就不解釋了 自己度娘、谷哥去
要不找個(gè)例子先?!
比如就拿www.iteye.com首頁(yè)來(lái)說(shuō)吧,我想定時(shí)抓取iteye首頁(yè)“精華文章”里面的數(shù)據(jù)
思路,用代碼請(qǐng)求www.iteye.com首頁(yè),拿到首頁(yè)的html代碼,解析html代碼,獲取“精華文章”里面文章的連接地址在此請(qǐng)求該地址,拿下該文章,是吧?!ok,來(lái)看處理過(guò)程:
先用瀏覽器打開www.iteye.com,可以用調(diào)試工具 firefox裝上firebug chrome右擊審核元素
以firefox為例:

可以發(fā)現(xiàn)“精華文章” 里面文章的全結(jié)構(gòu)是
在id=“page”的div下面的
id=“content”的div下面的
id=“main”的div下面的
class=“left”的div下面的
id=“recommend”的div下面的
ul下面的li下面的a標(biāo)簽
首先用httpClient獲取首頁(yè)html代碼 我用的是httpClient4.1.2 jar包見附件 jsoup用的是jsoup-1.6.1.jar
- /**
- * 根據(jù)URL獲得所有的html信息
- * @param url
- * @return
- */
- public static String getHtmlByUrl(String url){
- String html = null;
- HttpClient httpClient = new DefaultHttpClient();//創(chuàng)建httpClient對(duì)象
- HttpGet httpget = new HttpGet(url);//以get方式請(qǐng)求該URL
- try {
- HttpResponse responce = httpClient.execute(httpget);//得到responce對(duì)象
- int resStatu = responce.getStatusLine().getStatusCode();//返回碼
- if (resStatu==HttpStatus.SC_OK) {//200正常 其他就不對(duì)
- //獲得相應(yīng)實(shí)體
- HttpEntity entity = responce.getEntity();
- if (entity!=null) {
- html = EntityUtils.toString(entity);//獲得html源代碼
- }
- }
- } catch (Exception e) {
- System.out.println("訪問(wèn)【"+url+"】出現(xiàn)異常!");
- e.printStackTrace();
- } finally {
- httpClient.getConnectionManager().shutdown();
- }
- return html;
- }
上面是用httpClient獲取html源文件的代碼
下面就是對(duì)該html頁(yè)面進(jìn)行解析 得到我們想要的連接
下面是jsoup處理得到的html源碼
- import org.jsoup.Jsoup;
- import org.jsoup.nodes.Document;
- import org.jsoup.nodes.Element;
- import org.jsoup.select.Elements;
-
- public class JustTest {
- public static void main(String[] args) {
- String html = getHtmlByUrl("http://www.iteye.com/");
- if (html!=null&&!"".equals(html)) {
- Document doc = Jsoup.parse(html);
- Elements linksElements = doc.select("div#page>div#content>div#main>div.left>div#recommend>ul>li>a");
- //以上代碼的意思是 找id為“page”的div里面 id為“content”的div里面 id為“main”的div里面 class為“left”的div里面 id為“recommend”的div里面ul里面li里面a標(biāo)簽
- for (Element ele:linksElements) {
- String href = ele.attr("href");
- String title = ele.text();
- System.out.println(href+","+title);
- }
- }
- }
- }
其實(shí)jsoup的語(yǔ)法很簡(jiǎn)單,就是跟jquery一樣用“#”取id,用“.”取樣式位之后的數(shù)據(jù)
其實(shí)都很簡(jiǎn)單的,當(dāng)然,越規(guī)范的網(wǎng)頁(yè)分析起來(lái)越容易,要是網(wǎng)頁(yè)不規(guī)范就只好大家多寫點(diǎn)代碼咯
-----------------------------------------------------
Silence, the way to avoid many problems;
Smile, the way to solve many problems;