最近看到Gecoo爬蟲工具,感覺比較簡單好用,所有寫個DEMO測試一下,抓取網站 
http://zj.zjol.com.cn/home.html,主要抓取新聞的標題和發布時間做為抓取測試對象。抓取HTML節點通過像Jquery選擇器一樣選擇節點,非常方便,Gecco代碼主要利用注解實現來實現URL匹配,看起來比較簡潔美觀。
添加Maven依賴
<dependency> <groupId>com.geccocrawler</groupId> <artifactId>gecco</artifactId> <version>1.0.8</version></dependency>
編寫抓取列表頁面
@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;}@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));  }}編寫抓取祥情頁面
@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;}@PipelineName("zjNewsDetailPipeline")public class ZJNewsDetailPipeline implements Pipeline<ZJNewsDetail> {  public void process(ZJNewsDetail zjNewsDetail) {    System.out.println(zjNewsDetail.getTitle()+" "+zjNewsDetail.getCreateTime());  }}啟動主函數
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();  }}抓取結果


以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答