抓取网页新闻(本篇文章主要介绍了JAVA爬虫GeccoGecco工具抓取新闻实例)
优采云 发布时间: 2022-01-01 19:15抓取网页新闻(本篇文章主要介绍了JAVA爬虫GeccoGecco工具抓取新闻实例)
本文文章主要介绍JAVA爬虫Gecco工具抓取新闻实例,有一定参考价值,感兴趣的朋友可以参考。
我最近看到了 Gecoo 爬虫工具。感觉比较简单,好用。写个DEMO测试一下,抓起来网站
,主要抓取新闻的标题和发布时间作为爬取测试对象。通过像 Jquery 选择器一样选择节点来抓取 HTML 节点非常方便。 Gecco代码主要是通过注解来实现URL匹配,看起来更加简洁美观。
添加Maven依赖
com.geccocrawlergecco1.0.8
编写抓取列表页面
@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 newList; }
@PipelineName("zJNewsListPipelines") public class ZJNewsListPipelines implements Pipeline { 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 { 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(); } }
获取结果
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持html中文站。
以上是Java爬虫Gecco工具抓取新闻实例的详细内容。更多详情请关注其他相关html中文网站文章!