webmagic自訂儲存(mysql、redis儲存)

來源:互聯網
上載者:User

標籤:nts   html   否則   自訂   com   檔案   raw   控制台   processor   

在很多時候,我們使用webmagic爬取網站的時候,爬取的資料希望儲存在mysql、redis中。因此需要對其擴充,實行自訂PipeLine。首先我們瞭解一下webmagic 的四個基本組件

一、 WebMagic的四個組件1、Downloader

Downloader負責從互連網上下載頁面,以便後續處理。WebMagic預設使用了HttpClient作為下載工具。

2、PageProcessor

PageProcessor負責解析頁面,抽取有用資訊,以及發現新的連結。WebMagic使用Jsoup作為HTML解析工具,並基於其開發瞭解析XPath的工具Xsoup。

在這四個組件中,PageProcessor對於每個網站每個頁面都不一樣,是需要使用者定製的部分。

3、Scheduler

Scheduler負責管理待抓取的URL,以及一些去重的工作。WebMagic預設提供了JDK的記憶體隊列來管理URL,並用集合來進行去重。也支援使用Redis進行分布式管理。

除非項目有一些特殊的分布式需求,否則無需自己定製Scheduler。

4、Pipeline

Pipeline負責抽取結果的處理,包括計算、持久化到檔案、資料庫等。WebMagic預設提供了“輸出到控制台”和“儲存到檔案”兩種結果處理方案。

Pipeline定義了結果儲存的方式,如果你要儲存到指定資料庫,則需要編寫對應的Pipeline。對於一類需求一般只需編寫一個Pipeline。

二、自訂Pipeline,實現Pipeline介面,從寫process方法。
package com.mdd.pip.pipeLine;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import com.mdd.pip.model.ProxyIp;import com.mdd.pip.service.ProxyIpService;import us.codecraft.webmagic.ResultItems;import us.codecraft.webmagic.Task;import us.codecraft.webmagic.pipeline.Pipeline;@Componentpublic class DataPipeLine implements Pipeline {    @Autowired    private ProxyIpService proxyIpService;    /**     * mysql 儲存     */    /*     * public void process(ResultItems resultItems, Task task) {     * List<ProxyIp>proxyIpList = resultItems.get("proxyIpList");     * if(proxyIpList!=null&&!proxyIpList.isEmpty()){     * proxyIpService.saveProxyIpList(proxyIpList); }     *      * }     */    /**     * redis 儲存     */    public void process(ResultItems resultItems, Task task) {        List<ProxyIp> proxyIpList = resultItems.get("proxyIpList");        if (proxyIpList != null && !proxyIpList.isEmpty()) {            proxyIpService.saveProxyListIpInRedis(proxyIpList);        }    }}
ResultItems 對象本質是一個Map。因此要我們儲存對象的時候,只需要在爬取時把爬取得資料封裝成對象,儲存在
ResultItems 裡即可。如果有很多資料,則可以考慮用List儲存。
package com.mdd.pip.crawler;import java.util.ArrayList;import java.util.List;import org.apache.log4j.Logger;import org.jsoup.nodes.Document;import org.jsoup.nodes.Element;import org.jsoup.select.Elements;import org.springframework.stereotype.Component;import com.mdd.pip.model.ProxyIp;import us.codecraft.webmagic.Page;import us.codecraft.webmagic.Site;import us.codecraft.webmagic.processor.PageProcessor;/** * 熱刺代理網站ip抓取 *  * @author xwl 2017.6.3 */@Componentpublic class XiCiProxyIpCrawler implements PageProcessor {    private Logger logger = Logger.getLogger(XiCiProxyIpCrawler.class);    // 部分一:抓取網站的相關配置,包括編碼、抓取間隔、重試次數等    private Site site = Site.me().setCycleRetryTimes(3).setRetryTimes(3).setSleepTime(1000)            .setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0");    public Site getSite() {        return site;    }        public void process(Page page) {        Document html = page.getHtml().getDocument();        // 結果集        List<ProxyIp> proxyIpList = new ArrayList<ProxyIp>();        Elements trElements = html.getElementById("ip_list").getElementsByTag("tr");        for (Element trEle : trElements) {            Elements tdElements = trEle.getElementsByTag("td");            if (tdElements == null||tdElements.size()<=0) {                continue;            }            try {                ProxyIp proxyIp = new ProxyIp();                String ip = tdElements.get(1).text();                String proxyPort = tdElements.get(2).text();                String ipAddress = tdElements.get(3).text();                String anonymity = tdElements.get(4).text();                String proxyType = tdElements.get(5).text();                String aliveTime = tdElements.get(6).text();                proxyIp.setProxyIp(ip);                proxyIp.setProxyPort(Integer.parseInt(proxyPort));                proxyIp.setAliveTime(aliveTime);                proxyIp.setAnonymity(anonymity);                proxyIp.setIpAddress(ipAddress);                proxyIp.setProxyType(proxyType);                logger.info(proxyIp.getProxyIp()+":"+proxyIp.getProxyPort());                proxyIpList.add(proxyIp);            } catch (Exception e) {                logger.error("IP代理解析出錯!", e);            }        }        page.putField("proxyIpList", proxyIpList);    }}
page.putField("proxyIpList", proxyIpList);本質是設值到了ResultItems對象裡了。

這樣外掛程式式、定製化很值的我們借鑒。希望下一步看源碼。

參考:
http://webmagic.io/docs/zh/posts/ch1-overview/architecture.html

webmagic自訂儲存(mysql、redis儲存)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.