
1. 爬蟲(chóng)框架webmagic
WebMagic是一個(gè)簡(jiǎn)單靈活的爬蟲(chóng)框架。基于WebMagic,你可以快速開(kāi)發(fā)出一個(gè)高效、易維護(hù)的爬蟲(chóng)。
1.1 官網(wǎng)地址
官網(wǎng)文檔寫(xiě)的比較清楚,建議大家直接閱讀官方文檔,也可以閱讀下面的內(nèi)容。地址如下:
官網(wǎng):http://webmagic.io
中文文檔地址: http://webmagic.io/docs/zh/
English: http://webmagic.io/docs/en
2. webmagic與spring boot框架集成
spring boot與webmagic的結(jié)合主要有三個(gè)模塊,分別為爬取模塊Processor,入庫(kù)模塊Pipeline,向數(shù)據(jù)庫(kù)存入爬取數(shù)據(jù),和定時(shí)任務(wù)模塊Scheduled,復(fù)制定時(shí)爬取網(wǎng)站數(shù)據(jù)。
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
爬取簡(jiǎn)書(shū)首頁(yè)P(yáng)rocessor,分析簡(jiǎn)書(shū)首頁(yè)的頁(yè)面數(shù)據(jù),獲取響應(yīng)的簡(jiǎn)書(shū)鏈接和標(biāo)題,放入wegmagic的Page中,到入庫(kù)模塊取出添加到數(shù)據(jù)庫(kù)。代碼如下:
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:簡(jiǎn)書(shū)首頁(yè)爬蟲(chóng)
* 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.itdecent.cn";
@Override
public void process(Page page) {
if (page.getUrl().regex(list).match()) {
List<Selectable> list=page.getHtml().xpath("http://ul[@class='article-list thumbnails']/li").nodes();
for (Selectable s : list) {
String title=s.xpath("http://div/h4/a/text()").toString();
String link=s.xpath("http://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.itdecent.cn");
spider.addPipeline(new NewsPipeline());
spider.thread(5);
spider.setExitWhenComplete(true);
spider.start();
}
}
2.3 入庫(kù)模塊Pipeline
入庫(kù)模塊結(jié)合spring boot的Repository模塊一起組合成入庫(kù)方法,繼承webmagic的Pipeline,然后實(shí)現(xiàn)方法,在process方法中獲取爬蟲(chóng)模塊的數(shù)據(jù),然后調(diào)用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 定時(shí)任務(wù)模塊Scheduled
使用spring boot自帶的定時(shí)任務(wù)注解@Scheduled(cron = "0 0 0/2 * * ? "),每天從0天開(kāi)始,每?jī)蓚€(gè)小時(shí)執(zhí)行一次爬取任務(wù),在定時(shí)任務(wù)里調(diào)取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:新聞定時(shí)任務(wù)
* Created by shang on 16/8/22.
*/
@Component
public class NewsScheduled {
@Autowired
private NewsPipeline newsPipeline;
/**
* 簡(jiǎn)書(shū)
*/
@Scheduled(cron = "0 0 0/2 * * ? ")//從0點(diǎn)開(kāi)始,每2個(gè)小時(shí)執(zhí)行一次
public void jianShuScheduled() {
System.out.println("----開(kāi)始執(zhí)行簡(jiǎn)書(shū)定時(shí)任務(wù)");
Spider spider = Spider.create(new JianShuProcessor());
spider.addUrl("http://www.itdecent.cn");
spider.addPipeline(newsPipeline);
spider.thread(5);
spider.setExitWhenComplete(true);
spider.start();
spider.stop();
}
}
2.5 spring boot啟用定時(shí)任務(wù)
在spring boot的Application里啟用定時(shí)任務(wù)注解,@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. 結(jié)束語(yǔ)
使用webmagic是我在水花一現(xiàn)項(xiàng)目中爬取網(wǎng)站數(shù)據(jù)時(shí)使用的的爬蟲(chóng)框架,在綜合比較的其他幾個(gè)爬蟲(chóng)框架后,選擇了這個(gè)框架,這個(gè)框架比較簡(jiǎn)單易學(xué),且功能強(qiáng)大,我這里只使用了基本的功能,還有許多強(qiáng)大的功能都沒(méi)有使用。有興趣的可以去看看官方文檔!
有需要代碼的可以去我的github上去拉取相關(guān)代碼,此代碼在水花一現(xiàn)項(xiàng)目中使用過(guò)。
歡迎大家關(guān)注我的水花一現(xiàn)項(xiàng)目。
水花一現(xiàn)APP下載地址:https://www.pgyer.com/0qj6
微信公眾號(hào):水花一現(xiàn),shuihuayixian
Github:https://github.com/shangjing105
QQ:787019494