爬虫框架webmagic与spring boot的结合使用--转
原文地址:http://www.jianshu.com/p/c3fc3129407d
1. 爬虫框架webmagic
WebMagic是一个简单灵活的爬虫框架。基于WebMagic,你可以快速开发出一个高效、易维护的爬虫。
1.1 官网地址
官网文档写的比较清楚,建议大家直接阅读官方文档,也可以阅读下面的内容。地址如下:
中文文档地址: http://webmagic.io/docs/zh/
English: http://webmagic.io/docs/en
2. webmagic与spring boot框架集成
spring boot与webmagic的结合主要有三个模块,分别为爬取模块Processor,入库模块Pipeline,向数据库存入爬取数据,和定时任务模块Scheduled,复制定时爬取网站数据。
2.1 maven添加
<dependency>
<groupId>us.codecraft</groupId>
<artifactId>webmagic-core</artifactId>
<version>0.5.3</version>
</dependency>
<dependency>
<groupId>us.codecraft</groupId>
<artifactId>webmagic-extension</artifactId>
<version>0.5.3</version>
</dependency>
2.2 爬取模块Processor
爬取简书首页Processor,分析简书首页的页面数据,获取响应的简书链接和标题,放入wegmagic的Page中,到入库模块取出添加到数据库。代码如下:
package com.shang.spray.common.processor;
import com.shang.spray.entity.News;
import com.shang.spray.entity.Sources;
import com.shang.spray.pipeline.NewsPipeline;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Selectable;
import java.util.List;
/**
* info:简书首页爬虫
* Created by shang on 16/9/9.
*/
public class JianShuProcessor implements PageProcessor {
private Site site = Site.me()
.setDomain("jianshu.com")
.setSleepTime(100)
.setUserAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36");
;
public static final String list = "http://www.jianshu.com";
@Override
public void process(Page page) {
if (page.getUrl().regex(list).match()) {
List<Selectable> list=page.getHtml().xpath("//ul[@class='article-list thumbnails']/li").nodes();
for (Selectable s : list) {
String title=s.xpath("//div/h4/a/text()").toString();
String link=s.xpath("//div/h4").links().toString();
News news=new News();
news.setTitle(title);
news.setInfo(title);
news.setLink(link);
news.setSources(new Sources(5));
page.putField("news"+title, news);
}
}
}
@Override
public Site getSite() {
return site;
}
public static void main(String[] args) {
Spider spider=Spider.create(new JianShuProcessor());
spider.addUrl("http://www.jianshu.com");
spider.addPipeline(new NewsPipeline());
spider.thread(5);
spider.setExitWhenComplete(true);
spider.start();
}
}
2.3 入库模块Pipeline
入库模块结合spring boot的Repository模块一起组合成入库方法,继承webmagic的Pipeline,然后实现方法,在process方法中获取爬虫模块的数据,然后调用spring boot的save方法。代码如下:
package com.shang.spray.pipeline;
import com.shang.spray.entity.News;
import com.shang.spray.entity.Sources;
import com.shang.spray.repository.NewsRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Repository;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* info:新闻
* Created by shang on 16/8/22.
*/
@Repository
public class NewsPipeline implements Pipeline {
@Autowired
protected NewsRepository newsRepository;
@Override
public void process(ResultItems resultItems, Task task) {
for (Map.Entry<String, Object> entry : resultItems.getAll().entrySet()) {
if (entry.getKey().contains("news")) {
News news=(News) entry.getValue();
Specification<News> specification=new Specification<News>() {
@Override
public Predicate toPredicate(Root<News> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
return criteriaBuilder.and(criteriaBuilder.equal(root.get("link"),news.getLink()));
}
};
if (newsRepository.findOne(specification) == null) {//检查链接是否已存在
news.setAuthor("水花");
news.setTypeId(1);
news.setSort(1);
news.setStatus(1);
news.setExplicitLink(true);
news.setCreateDate(new Date());
news.setModifyDate(new Date());
newsRepository.save(news);
}
}
}
}
}
2.4 定时任务模块Scheduled
使用spring boot自带的定时任务注解@Scheduled(cron = "0 0 0/2 * * ? "),每天从0天开始,每两个小时执行一次爬取任务,在定时任务里调取webmagic的爬取模块Processor。代码如下:
package com.shang.spray.common.scheduled;
import com.shang.spray.common.processor.DevelopersProcessor;
import com.shang.spray.common.processor.JianShuProcessor;
import com.shang.spray.common.processor.ZhiHuProcessor;
import com.shang.spray.entity.Config;
import com.shang.spray.pipeline.NewsPipeline;
import com.shang.spray.service.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Spider;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
/**
* info:新闻定时任务
* Created by shang on 16/8/22.
*/
@Component
public class NewsScheduled {
@Autowired
private NewsPipeline newsPipeline;
/**
* 简书
*/
@Scheduled(cron = "0 0 0/2 * * ? ")//从0点开始,每2个小时执行一次
public void jianShuScheduled() {
System.out.println("----开始执行简书定时任务");
Spider spider = Spider.create(new JianShuProcessor());
spider.addUrl("http://www.jianshu.com");
spider.addPipeline(newsPipeline);
spider.thread(5);
spider.setExitWhenComplete(true);
spider.start();
spider.stop();
}
}
2.5 spring boot启用定时任务
在spring boot的Application里启用定时任务注解,@EnableScheduling。代码如下:
package com.shang.spray;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* info:
* Created by shang on 16/7/8.
*/
@Configuration
@EnableAutoConfiguration
@ComponentScan
@SpringBootApplication
@EnableScheduling
public class SprayApplication extends SpringBootServletInitializer{
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SprayApplication.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SprayApplication.class, args);
}
}
3. 结束语
使用webmagic是我在水花一现项目中爬取网站数据时使用的的爬虫框架,在综合比较的其他几个爬虫框架后,选择了这个框架,这个框架比较简单易学,且功能强大,我这里只使用了基本的功能,还有许多强大的功能都没有使用。有兴趣的可以去看看官方文档!
爬虫框架webmagic与spring boot的结合使用--转的更多相关文章
- 网络爬虫框架Webmagic
1 谈谈网络爬虫 1.1 什么是网络爬虫 在大数据时代,信息的采集是一项重要的工作,而互联网中的数据是海量的,如果单纯靠人力进行信息采集,不仅低效繁琐,搜集的成本也会提高.如何自动高效地获取互联网中我 ...
- RabbitMQ与Spring的框架整合之Spring Boot实战
1.RabbitMQ与Spring的框架整合之Spring Boot实战. 首先创建maven项目的RabbitMQ的消息生产者rabbitmq-springboot-provider项目,配置pom ...
- 爬虫框架--webmagic
官方有详细的使用文档:http://webmagic.io/docs/zh/ 简介:这只是个java爬虫框架,具体使用需要个人去定制,没有图片验证,不能获取js渲染的网页,但简单易用,可以通过xpat ...
- Java爬虫框架WebMagic——入门(爬取列表类网站文章)
初学爬虫,WebMagic作为一个Java开发的爬虫框架很容易上手,下面就通过一个简单的小例子来看一下. WebMagic框架简介 WebMagic框架包含四个组件,PageProcessor.Sch ...
- JAVA爬虫实践(实践三:爬虫框架webMagic和csdnBlog爬虫)
WebMagic WebMagic是一个简单灵活的Java爬虫框架.基于WebMagic,你可以快速开发出一个高效.易维护的爬虫. 采用HttpClient可以实现定向的爬虫,也可以自己编写算法逻辑来 ...
- 分享一个自搭的框架,使用Spring boot+Vue+Element UI
废弃,新的:https://www.cnblogs.com/hackyo/p/10453243.html 特点:前后端分离,可遵循restful 框架:后端使用Spring boot,整合了aop.a ...
- SSM框架优缺点和spring boot 比起优缺点是什么?
一.SSM优缺点应该分开来说的,比如 1)spring 不说了,核心ioc.aop技术,ioc解耦,使得代码复用,可维护性大幅度提升,aop提供切面编程,同样的增强了生产力. 2)spring mvc ...
- 框架-Java:Spring Boot
ylbtech-框架-Java:Spring Boot 1.返回顶部 1. Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该 ...
- Java爬虫框架WebMagic入门——爬取列表类网站文章
初学爬虫,WebMagic作为一个Java开发的爬虫框架很容易上手,下面就通过一个简单的小例子来看一下. WebMagic框架简介 WebMagic框架包含四个组件,PageProcessor.Sch ...
随机推荐
- 7.matlab字符串分析
1 字符串处理函数 clc; clear all; str='My name is Robin.'; disp(str); %字符串的输出 str_size=size(str) %字符串的长度 str ...
- vue中使用Ueditor编辑器 -- 1
一. 下载包: 从Ueditor的官网下载1.4.3.3jsp版本的Ueditor编辑器,官网地址为:http://ueditor.baidu.com/website/download.html ...
- css+html应用实例1:滑动门技术的简单实现
关于滑动门,现在的页面中好多地方都会用到滑动门,一般用作于导航背景,它的官方解释如下: 滑动门:根据文本自适应大小,根据背景的层叠性制作,并允许他们在彼此之上进行滑动,以创造出一些特殊的效果. 为什么 ...
- 使用最新vue_cli+webpack搭建的模版
使用最新vue_cli+webpack搭建的模版,包含了常用的插件,router和axiox与测试插件.项目的结构如下: 框架下载地址:https://share.weiyun.com/5Cl7EbU
- JAVA-mysql读写分离插件介绍
kingshard是一个由Go开发高性能MySQL Proxy项目,kingshard在满足基本的读写分离的功能上,致力于简化MySQL分库分表操作:能够让DBA通过kingshard轻松平滑地实现M ...
- Hessian 接口使用示例总结
一.使用hessian接口准备 首先,hessian接口的使用,必须要准备hessian接口的jar包,本文使用的jar包如下:hessian-4.0.7.jar; Hessian接口的使用一般是在两 ...
- 互联网时代: 从Uber的供需匹配看开发需求
每次看电影中的有钱人都有专属司机接送,只要坐在车里,就有人帮忙开车门.提行李及关车门.感觉是非现实的遥远画面,现在却有机会可以在日常生活中成真! 2009年Travis Kalanick及Garret ...
- Kattis -I Can Guess the Data Structure!
I Can Guess the Data Structure! There is a bag-like data structure, supporting two operations: 1 x1 ...
- selenim
一.安装selenium Pip install selenium==2.53.1 (稳定版) 下载火狐浏览器35.0.1 http://dl.pconline.com.cn/download ...
- windows下一台机器运行多个tomcat
一.将本机原有的tomcat配置不变, 二.下载新的tomcat解压版,地址:http://tomcat.apache.org/download-80.cgi 三.下载完成解压后,为了方便区分,最好将 ...