WebMagic學(xué)習(xí)(六)之自定義Pipeline(一個(gè)簡單的爬蟲)

Pipeline的接口

public interface Pipeline {

    /**
     * Process extracted results.
     * ResultItems保存了抽取結(jié)果,它是一個(gè)Map結(jié)構(gòu)裸准,在page.putField(key,value)中保存的數(shù)據(jù),可以通過ResultItems.get(key)獲取
     * @param resultItems resultItems
     * @param task task
     */
    public void process(ResultItems resultItems, Task task);
}
  • 將結(jié)果輸出到控制臺
    ConsolePipeline
public class ConsolePipeline implements Pipeline {

    @Override
    public void process(ResultItems resultItems, Task task) {
        System.out.println("get page: " + resultItems.getRequest().getUrl());
        for (Map.Entry<String, Object> entry : resultItems.getAll().entrySet()) {
            System.out.println(entry.getKey() + ":\t" + entry.getValue());
        }
    }
}
  • 將結(jié)果保存到MySQL窝剖,實(shí)現(xiàn)一個(gè)簡易爬蟲
    自定義pileline實(shí)現(xiàn)Pipeline接口欠拾,實(shí)現(xiàn)process方法,在該方法中將數(shù)據(jù)存入數(shù)據(jù)庫
package com.sima.crawler;
import com.sima.db.MysqlDBUtils;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.PageModelPipeline;
import us.codecraft.webmagic.pipeline.Pipeline;
/**
 * Created by cfq on 2017/4/30.
 */
public class GankDaoPipeline implements Pipeline {
    @Override
    public void process(ResultItems resultItems, Task task) {
        System.out.println("process");
        GankModel gankModel = new GankModel(resultItems.get("title").toString(), resultItems.get("content").toString());
        //可以存入數(shù)據(jù)庫
//        System.out.println(gankModel.getTitle());
        System.out.println("插入" + MysqlDBUtils.insert(gankModel) + "條數(shù)據(jù)治泥!");
    }
}

其中數(shù)據(jù)庫幫助類代碼如下,采用Druid進(jìn)行數(shù)據(jù)庫連接管理遮精。

public class MysqlDBUtils {
    private static Connection getConn() {
        String confile = "druid.properties";//配置文件名稱
        Properties properties = new Properties();
        InputStream inputStream = null;
        DruidDataSource dataSource = null;
        Connection connection = null;
        confile = MysqlDBUtils.class.getResource("/").getPath() + confile;//獲取配置文件路徑
        File file = new File(confile);
        try {
            inputStream = new BufferedInputStream(new FileInputStream(file));
            properties.load(inputStream);//加載配置文件

            //通過DruidDataSourceFactory獲取javax.sql.DataSource
            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
            connection = dataSource.getConnection();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static int insert(GankModel gankModel) {
        Connection conn = getConn();
        int i = 0;
        String sql = "insert into gankinfo (title,content) values(?,?)";
        PreparedStatement pstmt;
        try {
            pstmt = (PreparedStatement) conn.prepareStatement(sql);
            pstmt.setString(1, gankModel.getTitle());
            pstmt.setString(2, gankModel.getContent());
            i = pstmt.executeUpdate();
            pstmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return i;
    }
    }
}

druid配置內(nèi)容如下居夹,druid學(xué)習(xí)筆記

#基本屬性 url本冲、user准脂、password
url=jdbc:mysql://localhost:3306/istep?useUnicode=true&characterEncoding=utf-8
username=istep
password=istep
#配置初始化大小、最小檬洞、最大
initialSize=1
minIdle=1
maxActive=20
#配置獲取連接等待超時(shí)的時(shí)間
maxWait=60000
#配置間隔多久才進(jìn)行一次檢測狸膏,檢測需要關(guān)閉的空閑連接,單位是毫秒
timeBetweenEvictionRunsMillis=60000
#配置一個(gè)連接在池中最小生存的時(shí)間添怔,單位是毫秒
minEvictableIdleTimeMillis=300000
validationQuery=SELECT 'x'
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
#filters=config
#connectionProperties=config.decrypt=true;config.decrypt.key=MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIZcLMcxhrqm+TE10+o2KKI1eoVw1UdtRtBSpKggXkj460nBhO27QdahWZq0MlkwKEKYLyb79TZFdPov8V3pbdsCAwEAAQ==

Model代碼如下:

public class GankModel {

    int id;
    String title;
    String content;

    public GankModel() {
    }

    public GankModel(String title, String content) {
        this.title = title;
        this.content = content;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    @Override
    public String toString() {
        return "GankModel{" +
                "title='" + title + '\'' +
                ", content='" + content + '\'' +
                '}';
    }
}

爬蟲demo湾戳,在Processor加入自定義的GankDaoPipeline主流程代碼如下

addPipeline(new GankDaoPipeline())
public class GankRepoPageProcessor implements PageProcessor {
    //抓取網(wǎng)站的相關(guān)配置闷板,包括編碼、抓取間隔院塞、重試次數(shù)等
    private Site site = Site.me().setRetryTimes(3).setSleepTime(2000);

    // process是定制爬蟲邏輯的核心接口,在這里編寫抽取邏輯
    public void process(Page page) {
        //定義如何抽取頁面信息
        //爬取干貨集中營歷史數(shù)據(jù)性昭,http://gank.io/2017/04/26
        page.addTargetRequests(page.getHtml().links().regex("(http://gank\\.io/\\d+/\\d+/\\d+)").all());
        page.putField("title", page.getHtml().$("h1").toString());//獲取標(biāo)題
        page.putField("content", page.getHtml().$("div.outlink").toString());//獲取頁面內(nèi)容
        if (page.getResultItems().get("title") == null) {
            //跳過沒有數(shù)據(jù)的頁面
            page.setSkip(true);
        }
    }

    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {
        Spider.create(new GankRepoPageProcessor())
                .addUrl("http://gank.io")//從該url開始
                .addPipeline(new GankDaoPipeline())
                .thread(5)
                .run();
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末拦止,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子糜颠,更是在濱河造成了極大的恐慌汹族,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,734評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件其兴,死亡現(xiàn)場離奇詭異顶瞒,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)元旬,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,931評論 3 394
  • 文/潘曉璐 我一進(jìn)店門榴徐,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人匀归,你說我怎么就攤上這事坑资。” “怎么了穆端?”我有些...
    開封第一講書人閱讀 164,133評論 0 354
  • 文/不壞的土叔 我叫張陵袱贮,是天一觀的道長。 經(jīng)常有香客問我体啰,道長攒巍,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,532評論 1 293
  • 正文 為了忘掉前任荒勇,我火速辦了婚禮柒莉,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘枕屉。我一直安慰自己常柄,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,585評論 6 392
  • 文/花漫 我一把揭開白布搀擂。 她就那樣靜靜地躺著西潘,像睡著了一般。 火紅的嫁衣襯著肌膚如雪哨颂。 梳的紋絲不亂的頭發(fā)上喷市,一...
    開封第一講書人閱讀 51,462評論 1 302
  • 那天,我揣著相機(jī)與錄音威恼,去河邊找鬼品姓。 笑死寝并,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的腹备。 我是一名探鬼主播衬潦,決...
    沈念sama閱讀 40,262評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼植酥!你這毒婦竟也來了镀岛?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,153評論 0 276
  • 序言:老撾萬榮一對情侶失蹤友驮,失蹤者是張志新(化名)和其女友劉穎漂羊,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體卸留,經(jīng)...
    沈念sama閱讀 45,587評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡走越,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,792評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了耻瑟。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片旨指。...
    茶點(diǎn)故事閱讀 39,919評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖喳整,靈堂內(nèi)的尸體忽然破棺而出淤毛,到底是詐尸還是另有隱情,我是刑警寧澤算柳,帶...
    沈念sama閱讀 35,635評論 5 345
  • 正文 年R本政府宣布低淡,位于F島的核電站,受9級特大地震影響瞬项,放射性物質(zhì)發(fā)生泄漏蔗蹋。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,237評論 3 329
  • 文/蒙蒙 一囱淋、第九天 我趴在偏房一處隱蔽的房頂上張望猪杭。 院中可真熱鬧,春花似錦妥衣、人聲如沸皂吮。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,855評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽蜂筹。三九已至,卻和暖如春芦倒,著一層夾襖步出監(jiān)牢的瞬間艺挪,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,983評論 1 269
  • 我被黑心中介騙來泰國打工兵扬, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留麻裳,地道東北人口蝠。 一個(gè)月前我還...
    沈念sama閱讀 48,048評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像津坑,于是被迫代替她去往敵國和親妙蔗。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,864評論 2 354

推薦閱讀更多精彩內(nèi)容