原文地址:http://www.jianshu.com/p/c3fc3129407d

1. 爬虫框架webmagic

WebMagic是一个简单灵活的爬虫框架。基于WebMagic,你可以快速开发出一个高效、易维护的爬虫。

1.1 官网地址

官网文档写的比较清楚,建议大家直接阅读官方文档,也可以阅读下面的内容。地址如下:

官网:http://webmagic.io

中文文档地址: http://webmagic.io/docs/zh/

English: http://webmagic.io/docs/en

2. webmagic与spring boot框架集成

spring bootwebmagic的结合主要有三个模块,分别为爬取模块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的结合使用--转的更多相关文章

  1. 网络爬虫框架Webmagic

    1 谈谈网络爬虫 1.1 什么是网络爬虫 在大数据时代,信息的采集是一项重要的工作,而互联网中的数据是海量的,如果单纯靠人力进行信息采集,不仅低效繁琐,搜集的成本也会提高.如何自动高效地获取互联网中我 ...

  2. RabbitMQ与Spring的框架整合之Spring Boot实战

    1.RabbitMQ与Spring的框架整合之Spring Boot实战. 首先创建maven项目的RabbitMQ的消息生产者rabbitmq-springboot-provider项目,配置pom ...

  3. 爬虫框架--webmagic

    官方有详细的使用文档:http://webmagic.io/docs/zh/ 简介:这只是个java爬虫框架,具体使用需要个人去定制,没有图片验证,不能获取js渲染的网页,但简单易用,可以通过xpat ...

  4. Java爬虫框架WebMagic——入门(爬取列表类网站文章)

    初学爬虫,WebMagic作为一个Java开发的爬虫框架很容易上手,下面就通过一个简单的小例子来看一下. WebMagic框架简介 WebMagic框架包含四个组件,PageProcessor.Sch ...

  5. JAVA爬虫实践(实践三:爬虫框架webMagic和csdnBlog爬虫)

    WebMagic WebMagic是一个简单灵活的Java爬虫框架.基于WebMagic,你可以快速开发出一个高效.易维护的爬虫. 采用HttpClient可以实现定向的爬虫,也可以自己编写算法逻辑来 ...

  6. 分享一个自搭的框架,使用Spring boot+Vue+Element UI

    废弃,新的:https://www.cnblogs.com/hackyo/p/10453243.html 特点:前后端分离,可遵循restful 框架:后端使用Spring boot,整合了aop.a ...

  7. SSM框架优缺点和spring boot 比起优缺点是什么?

    一.SSM优缺点应该分开来说的,比如 1)spring 不说了,核心ioc.aop技术,ioc解耦,使得代码复用,可维护性大幅度提升,aop提供切面编程,同样的增强了生产力. 2)spring mvc ...

  8. 框架-Java:Spring Boot

    ylbtech-框架-Java:Spring Boot 1.返回顶部 1. Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该 ...

  9. Java爬虫框架WebMagic入门——爬取列表类网站文章

    初学爬虫,WebMagic作为一个Java开发的爬虫框架很容易上手,下面就通过一个简单的小例子来看一下. WebMagic框架简介 WebMagic框架包含四个组件,PageProcessor.Sch ...

随机推荐

  1. Linux性能优化和监控系列(一)——top工具

    解释服务器发生了什么——top工具 在检查服务器的详细工作性能状态前,系统管理员需要对当前服务器状态有总体的了解. top是检查服务器总体状态的强有力工具, 通过top可以获取CPU, Memory, ...

  2. CentOS 7 NAT模式上网配置

    一 VMware 配置 在“编辑”选项卡中,选择“虚拟网络编辑器”,如下图: 选择VMnet8,修改子网IP与子网掩码,注意不要给“使用本地DHCP服务将IP地址分配给虚拟机”选项打勾,如下图: 点击 ...

  3. POJ 3020 Hungary

    一道建图题-- // by SiriusRen #include <cstdio> #include <cstring> using namespace std; #defin ...

  4. HD-ACM算法专攻系列(16)——考试排名

    问题描述: 源码: 主要要注意输出格式. #include"iostream" #include"iomanip" #include"algorith ...

  5. rel= "noopener"

    rel= "noopener" <a href= "https://www.xiaogezi.cn/" target= "_blank" ...

  6. P1903 【模板】分块/带修改莫队(数颜色)

    题目描述 墨墨购买了一套N支彩色画笔(其中有些颜色可能相同),摆成一排,你需要回答墨墨的提问.墨墨会像你发布如下指令: 1. Q L R代表询问你从第L支画笔到第R支画笔中共有几种不同颜色的画笔. 2 ...

  7. 编码介绍(ANSI、GBK、GB2312、UTF-8、GB18030和 UNICODE)

    转载:http://blog.jobbole.com/30526/(前面内容)和http://www.ruanyifeng.com/blog/2007/10/ascii_unicode_and_utf ...

  8. c++ sort函数的用法

    C++ sort函数用法 FROM:http://hi.baidu.com/blackdemonfish/blog/item/e2c1d655d702a45ed0090652%2Ehtml 最近算法作 ...

  9. done

  10. ItChat与图灵机器人的结合

    前景: 我在知乎关注一位大佬 名字叫 LittleCoder 我是在他开发ItChat包时关注的 ItChat已经完成了微信的个人账号的API接口 已经实现了实时获取用户的即时信息并自动化进行回应 后 ...