最近看到Gecoo爬蟲工具,感覺比較簡單好用,所有寫個DEMO測試一下,抓取網(wǎng)站
http://zj.zjol.com.cn/home.html,主要抓取新聞的標題和發(fā)布時間做為抓取測試對象。抓取HTML節(jié)點通過像Jquery選擇器一樣選擇節(jié)點,非常方便,Gecco代碼主要利用注解實現(xiàn)來實現(xiàn)URL匹配,看起來比較簡潔美觀。
添加Maven依賴
1
2
3
4
5
|
< dependency > < groupId >com.geccocrawler</ groupId > < artifactId >gecco</ artifactId > < version >1.0.8</ version > </ dependency > |
編寫抓取列表頁面
1
2
3
4
5
6
7
8
9
10
11
|
@Gecco (matchUrl = "http://zj.zjol.com.cn/home.html?pageIndex={pageIndex}&pageSize={pageSize}" ,pipelines = "zJNewsListPipelines" ) public class ZJNewsGeccoList implements HtmlBean { @Request private HttpRequest request; @RequestParameter private int pageIndex; @RequestParameter private int pageSize; @HtmlField (cssPath = "#content > div > div > div.con_index > div.r.main_mod > div > ul > li > dl > dt > a" ) private List<HrefBean> newList; } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
@PipelineName ( "zJNewsListPipelines" ) public class ZJNewsListPipelines implements Pipeline<ZJNewsGeccoList> { public void process(ZJNewsGeccoList zjNewsGeccoList) { HttpRequest request=zjNewsGeccoList.getRequest(); for (HrefBean bean:zjNewsGeccoList.getNewList()){ //進入祥情頁面抓取 SchedulerContext.into(request.subRequest( "http://zj.zjol.com.cn" +bean.getUrl())); } int page=zjNewsGeccoList.getPageIndex()+ 1 ; String nextUrl = "http://zj.zjol.com.cn/home.html?pageIndex=" +page+ "&pageSize=100" ; //抓取下一頁 SchedulerContext.into(request.subRequest(nextUrl)); } } |
編寫抓取祥情頁面
1
2
3
4
5
6
7
8
9
10
11
|
@Gecco (matchUrl = "http://zj.zjol.com.cn/news/[code].html" ,pipelines = "zjNewsDetailPipeline" ) public class ZJNewsDetail implements HtmlBean { @Text @HtmlField (cssPath = "#headline" ) private String title ; @Text @HtmlField (cssPath = "#content > div > div.news_con > div.news-content > div:nth-child(1) > div > p.go-left.post-time.c-gray" ) private String createTime; } |
1
2
3
4
5
6
|
@PipelineName ( "zjNewsDetailPipeline" ) public class ZJNewsDetailPipeline implements Pipeline<ZJNewsDetail> { public void process(ZJNewsDetail zjNewsDetail) { System.out.println(zjNewsDetail.getTitle()+ " " +zjNewsDetail.getCreateTime()); } } |
啟動主函數(shù)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class Main { public static void main(String [] rags){ GeccoEngine.create() //工程的包路徑 .classpath( "com.zhaochao.gecco.zj" ) //開始抓取的頁面地址 .start( "http://zj.zjol.com.cn/home.html?pageIndex=1&pageSize=100" ) //開啟幾個爬蟲線程 .thread( 10 ) //單個爬蟲每次抓取完一個請求后的間隔時間 .interval( 10 ) //使用pc端userAgent .mobile( false ) //開始運行 .run(); } } |
抓取結(jié)果
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持服務(wù)器之家。