流世幻羽

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

  WebMagic介绍

WebMagic项目代码分为核心和扩展两部分。核心部分(webmagic-core)是一个精简的、模块化的爬虫实现,而扩展部分则包括一些便利的、实用性的功能。

WebMagic的设计目标是尽量的模块化,并体现爬虫的功能特点。这部分提供非常简单、灵活的API,在基本不改变开发模式的情况下,编写一个爬虫。

扩展部分(webmagic-extension)提供一些便捷的功能,例如注解模式编写爬虫等。同时内置了一些常用的组件,便于爬虫开发

WebMagic的结构分为DownloaderPageProcessorSchedulerPipeline四大组件,并由Spider将它们彼此组织起来。这四大组件对应爬虫生命周期中的下载、处理、管理和持久化等功能。WebMagic的设计参考了Scapy,但是实现方式更Java化一些。

Spider则将这几个组件组织起来,让它们可以互相交互,流程化的执行,可以认为Spider是一个大的容器,它也是WebMagic逻辑的核心。

WebMagic总体架构图如下:

 

 

 WebMagic的四个组件

1.Downloader

Downloader负责从互联网上下载页面,以便后续处理。WebMagic默认使用了Apache HttpClient作为下载工具。

 

2.PageProcessor

PageProcessor负责解析页面,抽取有用信息,以及发现新的链接。WebMagic使用Jsoup作为HTML解析工具,并基于其开发了解析XPath的工具Xsoup。

 

在这四个组件中,PageProcessor对于每个站点每个页面都不一样,是需要使用者定制的部分。

 

3.Scheduler

Scheduler负责管理待抓取的URL,以及一些去重的工作。WebMagic默认提供了JDK的内存队列来管理URL,并用集合来进行去重。也支持使用Redis进行分布式管理。

 

4.Pipeline

Pipeline负责抽取结果的处理,包括计算、持久化到文件、数据库等。WebMagic默认提供了“输出到控制台”和“保存到文件”两种结果处理方案。

 

Pipeline定义了结果保存的方式,如果你要保存到指定数据库,则需要编写对应的Pipeline。对于一类需求一般只需编写一个Pipeline。

 

 用于数据流转的对象

Request

Request是对URL地址的一层封装,一个Request对应一个URL地址。

 

它是PageProcessor与Downloader交互的载体,也是PageProcessor控制Downloader唯一方式。

 

除了URL本身外,它还包含一个Key-Value结构的字段extra。你可以在extra中保存一些特殊的属性,然后在其他地方读取,以完成不同的功能。例如附加上一个页面的一些信息等。

 

2. Page

Page代表了从Downloader下载到的一个页面——可能是HTML,也可能是JSON或者其他文本格式的内容。

 

Page是WebMagic抽取过程的核心对象,它提供一些方法可供抽取、结果保存等。

 

3. ResultItems

ResultItems相当于一个Map,它保存PageProcessor处理的结果,供Pipeline使用。它的API与Map很类似,值得注意的是它有一个字段skip,若设置为true,则不应被Pipeline处理。

WebMagic功能

实现PageProcessor

WebMagic里主要使用了三种抽取技术:XPath、正则表达式和CSS选择器。另外,对于JSON格式的内容,可使用JsonPath进行解析。

 XPath

以上是获取属性class=mt的div标签,里面的h1标签的内容

page.getHtml().xpath("//div[@class=mt]/h1/text()")

CSS选择器

CSS选择器是与XPath类似的语言。在上一次的课程中,我们已经学习过了Jsoup的选择器,它比XPath写起来要简单一些,但是如果写复杂一点的抽取规则,就相对要麻烦一点。

div.mt>h1表示class为mt的div标签下的直接子元素h1标签

page.getHtml().css("div.mt>h1").toString()

可是使用:nth-child(n)选择第几个元素,如下选择第一个元素

page.getHtml().css("div#news_div > ul > li:nth-child(1) a").toString()

注意:需要使用>,就是直接子元素才可以选择第几个元素

正则表达式

正则表达式则是一种通用的文本抽取语言。在这里一般用于获取url地址。

 抽取元素API

Selectable相关的抽取元素链式API是WebMagic的一个核心功能。使用Selectable接口,可以直接完成页面元素的链式抽取,也无需去关心抽取的细节。

page.getHtml()返回的是一个Html对象,它实现了Selectable接口。这个接口包含的方法分为两类:抽取部分和获取结果部分。

 

方法

说明

示例

xpath(String xpath)

使用XPath选择

html.xpath("//div[@class='title']")

$(String selector)

使用Css选择器选择

html.$("div.title")

$(String selector,String attr)

使用Css选择器选择

html.$("div.title","text")

css(String selector)

功能同$(),使用Css选择器选择

html.css("div.title")

links()

选择所有链接

html.links()

regex(String regex)

使用正则表达式抽取

html.regex("\(.\*?)\")

 获取结果API

当链式调用结束时,我们一般都想要拿到一个字符串类型的结果。这时候就需要用到获取结果的API了。

一条抽取规则,无论是XPath、CSS选择器或者正则表达式,总有可能抽取到多条元素。WebMagic对这些进行了统一,可以通过不同的API获取到一个或者多个元素。

方法

说明

示例

get()

返回一条String类型的结果

String link= html.links().get()

toString()

同get(),返回一条String类型的结果

String link= html.links().toString()

all()

返回所有抽取结果

List links= html.links().all()

当有多条数据的时候,使用get()和toString()都是获取第一个url地址。

String str = page.getHtml()
        .css("div#news_div")
        .links().regex(".*[0-3]$").toString();

String get = page.getHtml()
        .css("div#news_div")
        .links().regex(".*[0-3]$").get();

 使用Pipeline保存结果

WebMagic用于保存结果的组件叫做Pipeline。我们现在通过“控制台输出结果”这件事也是通过一个内置的Pipeline完成的,它叫做ConsolePipeline

 

那么,我现在想要把结果用保存到文件中,怎么做呢?只将Pipeline的实现换成"FilePipeline"就可以了。

public static void main(String[] args) {
    Spider.create(new JobProcessor())
            //初始访问url地址
            .addUrl("https://www.jd.com/moreSubject.aspx")
            .addPipeline(new FilePipeline("D:/webmagic/"))
            .thread(5)//设置线程数
            .run();
}

 爬虫的配置、启动和终止

Spider是爬虫启动的入口。在启动爬虫之前,我们需要使用一个PageProcessor创建一个Spider对象,然后使用run()进行启动。

 

同时Spider的其他组件(Downloader、Scheduler、Pipeline)都可以通过set方法来进行设置。

方法

说明

示例

create(PageProcessor)

创建Spider

Spider.create(new GithubRepoProcessor())

addUrl(String…)

添加初始的URL

spider .addUrl("http://webmagic.io/docs/")

thread(n)

开启n个线程

spider.thread(5)

run()

启动,会阻塞当前线程执行

spider.run()

start()/runAsync()

异步启动,当前线程继续执行

spider.start()

stop()

停止爬虫

spider.stop()

addPipeline(Pipeline)

添加一个Pipeline,一个Spider可以有多个Pipeline

spider .addPipeline(new ConsolePipeline())

setScheduler(Scheduler)

设置Scheduler,一个Spider只能有个一个Scheduler

spider.setScheduler(new RedisScheduler())

setDownloader(Downloader)

设置Downloader,一个Spider只能有个一个Downloader

spider .setDownloader(

new SeleniumDownloader())

get(String)

同步调用,并直接取得结果

ResultItems result = spider

.get("http://webmagic.io/docs/")

getAll(String…)

同步调用,并直接取得一堆结果

List<ResultItems> results = spider

.getAll("http://webmagic.io/docs/", "http://webmagic.io/xxx")

 

 爬虫配置Site

Site.me()可以对爬虫进行一些配置配置,包括编码、抓取间隔、超时时间、重试次数等。在这里我们先简单设置一下:重试次数为3次,抓取间隔为一秒。

      private Site site = Site.me()
        .setCharset("UTF-8")//编码
        .setSleepTime(1)//抓取间隔时间
        .setTimeOut(1000*10)//超时时间
        .setRetrySleepTime(3000)//重试时间
        .setRetryTimes(3);//重试次数

站点本身的一些配置信息,例如编码、HTTP头、超时时间、重试策略等、代理等,都可以通过设置Site对象来进行配置。

方法

说明

示例

setCharset(String)

设置编码

site.setCharset("utf-8")

setUserAgent(String)

设置UserAgent

site.setUserAgent("Spider")

setTimeOut(int)

设置超时时间,

单位是毫秒

site.setTimeOut(3000)

setRetryTimes(int)

设置重试次数

site.setRetryTimes(3)

setCycleRetryTimes(int)

设置循环重试次数

site.setCycleRetryTimes(3)

addCookie(String,String)

添加一条cookie

site.addCookie("dotcomt_user","code4craft")

setDomain(String)

设置域名,需设置域名后,addCookie才可生效

site.setDomain("github.com")

addHeader(String,String)

添加一条addHeader

site.addHeader("Referer","https://github.com")

setHttpProxy(HttpHost)

设置Http代理

site.setHttpProxy(new HttpHost("127.0.0.1",8080))

  爬虫分类

网络爬虫按照系统结构和实现技术,大致可以分为以下几种类型:通用网络爬虫、聚焦网络爬虫、增量式网络爬虫、深层网络爬虫。 实际的网络爬虫系统通常是几种爬虫技术相结合实现的

 通用网络爬虫

通用网络爬虫又称全网爬虫(Scalable Web Crawler),爬行对象从一些种子 URL 扩充到整个 Web,主要为门户站点搜索引擎和大型 Web 服务提供商采集数据。

这类网络爬虫的爬行范围和数量巨大,对于爬行速度和存储空间要求较高,对于爬行页面的顺序要求相对较低,同时由于待刷新的页面太多,通常采用并行工作方式,但需要较长时间才能刷新一次页面。

简单的说就是互联网上抓取所有数据。

 

 聚焦网络爬虫

聚焦网络爬虫(Focused Crawler),又称主题网络爬虫(Topical Crawler),是指选择性地爬行那些与预先定义好的主题相关页面的网络爬虫。

和通用网络爬虫相比,聚焦爬虫只需要爬行与主题相关的页面,极大地节省了硬件和网络资源,保存的页面也由于数量少而更新快,还可以很好地满足一些特定人群对特定领域信息的需求 。

简单的说就是互联网上只抓取某一种数据。

 

 增量式网络爬虫

增量式网络爬虫(Incremental Web Crawler)是 指 对 已 下 载 网 页 采 取 增量式更新和只爬行新产生的或者已经发生变化网页的爬虫,它能够在一定程度上保证所爬行的页面是尽可能新的页面。

和周期性爬行和刷新页面的网络爬虫相比,增量式爬虫只会在需要的时候爬行新产生或发生更新的页面 ,并不重新下载没有发生变化的页面,可有效减少数据下载量,及时更新已爬行的网页,减小时间和空间上的耗费,但是增加了爬行算法的复杂度和实现难度。

简单的说就是互联网上只抓取刚刚更新的数据。

 

 Deep Web 爬虫

Web 页面按存在方式可以分为表层网页(Surface Web)和深层网页(Deep Web,也称 Invisible Web Pages 或 Hidden Web)。

表层网页是指传统搜索引擎可以索引的页面,以超链接可以到达的静态网页为主构成的 Web 页面。

Deep Web 是那些大部分内容不能通过静态链接获取的、隐藏在搜索表单后的,只有用户提交一些关键词才能获得的 Web 页面.

1.pom

 <dependencies>
        <!--SpringMVC-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--SpringData Jpa-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!--MySQL连接包-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!-- HttpClient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>

        <!--Jsoup-->
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.10.3</version>
        </dependency>

        <!--工具包-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

 

#DB Configuration:
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/crawler
spring.datasource.username=root
spring.datasource.password=

#JPA Configuration:
spring.jpa.database=MySQL
spring.jpa.show-sql=true
@SpringBootApplication
//使用定时任务,需要先开启定时任务,需要添加注解
@EnableScheduling
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

  

  

2.工具类

 

@Component
public class HttpUtils {

    private PoolingHttpClientConnectionManager cm;

    public HttpUtils() {
        this.cm = new PoolingHttpClientConnectionManager();

        //设置最大连接数
        this.cm.setMaxTotal(100);

        //设置每个主机的最大连接数
        this.cm.setDefaultMaxPerRoute(10);
    }

    /**
     * 根据请求地址下载页面数据
     *
     * @param url
     * @return 页面数据
     */
    public String doGetHtml(String url) {
        //获取HttpClient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(this.cm).build();

        //创建httpGet请求对象,设置url地址
        HttpGet httpGet = new HttpGet(url);

        //设置请求信息
        httpGet.setConfig(this.getConfig());

        CloseableHttpResponse response = null;


        try {
            //使用HttpClient发起请求,获取响应
            response = httpClient.execute(httpGet);

            //解析响应,返回结果
            if (response.getStatusLine().getStatusCode() == 200) {
                //判断响应体Entity是否不为空,如果不为空就可以使用EntityUtils
                if (response.getEntity() != null) {
                    String content = EntityUtils.toString(response.getEntity(), "utf8");
                    return content;
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭response
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //返回空串
        return "";
    }


    /**
     * 下载图片
     *
     * @param url
     * @return 图片名称
     */
    public String doGetImage(String url) {
        //获取HttpClient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(this.cm).build();

        //创建httpGet请求对象,设置url地址
        HttpGet httpGet = new HttpGet(url);

        //设置请求信息
        httpGet.setConfig(this.getConfig());

        CloseableHttpResponse response = null;


        try {
            //使用HttpClient发起请求,获取响应
            response = httpClient.execute(httpGet);

            //解析响应,返回结果
            if (response.getStatusLine().getStatusCode() == 200) {
                //判断响应体Entity是否不为空
                if (response.getEntity() != null) {
                    //下载图片
                    //获取图片的后缀
                    String extName = url.substring(url.lastIndexOf("."));

                    //创建图片名,重命名图片
                    String picName = UUID.randomUUID().toString() + extName;

                    //下载图片
                    //声明OutPutStream
                    OutputStream outputStream = new FileOutputStream(new File("C:\\Users\\tree\\Desktop\\images\\" +
                            picName));
                    response.getEntity().writeTo(outputStream);

                    //返回图片名称
                    return picName;
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭response
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //如果下载失败,返回空串
        return "";
    }

    //设置请求信息
    private RequestConfig getConfig() {
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(1000)    //创建连接的最长时间
                .setConnectionRequestTimeout(500)  // 获取连接的最长时间
                .setSocketTimeout(10000)    //数据传输的最长时间
                .build();

        return config;
    }

 

@Entity
@Table(name = "jd_item")
public class Item {
    //主键
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    //标准产品单位(商品集合)
    private Long spu;
    //库存量单位(最小品类单元)
    private Long sku;
    //商品标题
    private String title;
    //商品价格
    private Double price;
    //商品图片
    private String pic;
    //商品详情地址
    private String url;
    //创建时间
    private Date created;
    //更新时间
    private Date updated;
}

3.service

public interface ItemService {

    /**
     * 保存商品
     * @param item
     */
    public void save(Item item);

    /**
     * 根据条件查询商品
     * @param item
     * @return
     */
    public List<Item> findAll(Item item);
}
@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    private ItemDao itemDao;

    @Override
    @Transactional
    public void save(Item item) {
        this.itemDao.save(item);
    }

    @Override
    public List<Item> findAll(Item item) {
        //声明查询条件
        Example<Item> example = Example.of(item);

        //根据查询条件进行查询数据
        List<Item> list = this.itemDao.findAll(example);

        return list;
    }
}

 

4.dao

public interface ItemDao extends JpaRepository<Item,Long> {
}

 

5.task

 1 @Component
 2 public class ItemTask {
 3 
 4     @Autowired
 5     private HttpUtils httpUtils;
 6     @Autowired
 7     private ItemService itemService;
 8 
 9     private static final ObjectMapper MAPPER =  new ObjectMapper();
10 
11 
12     //当下载任务完成后,间隔多长时间进行下一次的任务。
13     @Scheduled(fixedDelay = 10 * 1000)
14     public void itemTask() throws Exception {
15         //声明需要解析的初始地址
16         String url = "https://search.jd.com/Search?keyword=%E6%89%8B%E6%9C%BA&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&wq" +
17                 "=%E6%89%8B%E6%9C%BA&cid2=653&cid3=655&s=113&click=0&page=";
18 
19         //按照页面对手机的搜索结果进行遍历解析
20         for (int i = 1; i < 10; i = i + 2) {
21             String html = httpUtils.doGetHtml(url + i);
22 
23             //解析页面,获取商品数据并存储
24             this.parse(html);
25         }
26 
27 
28         System.out.println("手机数据抓取完成!");
29 
30 
31     }
32 
33     //解析页面,获取商品数据并存储
34     private void parse(String html) throws Exception {
35         //解析html获取Document
36         Document doc = Jsoup.parse(html);
37 
38         //获取spu信息
39         Elements spuEles = doc.select("div#J_goodsList > ul > li");
40 
41         for (Element spuEle : spuEles) {
42             //获取spu
43             long spu = Long.parseLong(spuEle.attr("data-spu"));
44 
45             //获取sku信息
46             Elements skuEles = spuEle.select("li.ps-item");
47 
48             for (Element skuEle : skuEles) {
49                 //获取sku
50                 long sku = Long.parseLong(skuEle.select("[data-sku]").attr("data-sku"));
51 
52                 //根据sku查询商品数据
53                 Item item = new Item();
54                 item.setSku(sku);
55                 List<Item> list = this.itemService.findAll(item);
56 
57                 if(list.size()>0) {
58                     //如果商品存在,就进行下一个循环,该商品不保存,因为已存在
59                     continue;
60                 }
61 
62                 //设置商品的spu
63                 item.setSpu(spu);
64 
65                 //获取商品的详情的url
66                 String itemUrl = "https://item.jd.com/" + sku + ".html";
67                 item.setUrl(itemUrl);
68 
69 
70                 //获取商品的图片
71                 String picUrl ="https:"+ skuEle.select("img[data-sku]").first().attr("data-lazy-img");
72                 picUrl = picUrl.replace("/n9/","/n1/");
73                 String picName = this.httpUtils.doGetImage(picUrl);
74                 item.setPic(picName);
75 
76                 //获取商品的价格
77                 String priceJson = this.httpUtils.doGetHtml("https://p.3.cn/prices/mgets?skuIds=J_" + sku);
78                 double price = MAPPER.readTree(priceJson).get(0).get("p").asDouble();
79                 item.setPrice(price);
80 
81 
82                 //获取商品的标题
83                 String itemInfo = this.httpUtils.doGetHtml(item.getUrl());
84                 String title = Jsoup.parse(itemInfo).select("div.sku-name").text();
85                 item.setTitle(title);
86 
87 
88                 item.setCreated(new Date());
89                 item.setUpdated(item.getCreated());
90 
91                 //保存商品数据到数据库中
92                 this.itemService.save(item);
93 
94             }
95         }
96     }
97 }

 

WebMagic项目代码分为核心和扩展两部分。核心部分(webmagic-core)是一个精简的、模块化的爬虫实现,而扩展部分则包括一些便利的、实用性的功能。

 

WebMagic的设计目标是尽量的模块化,并体现爬虫的功能特点。这部分提供非常简单、灵活的API,在基本不改变开发模式的情况下,编写一个爬虫。

 

扩展部分(webmagic-extension)提供一些便捷的功能,例如注解模式编写爬虫等。同时内置了一些常用的组件,便于爬虫开发

posted on 2019-08-09 15:32  流世幻羽  阅读(767)  评论(0编辑  收藏  举报