Java實現網絡爬蟲 案例代碼4:使用webmagic框架從網上獲取《三國演義》全文

案例4:從網上獲取《三國演義》全文

需求說明

搭建開發環境,實現《三國演義》全文保存在本地

步驟分析

訪問網址:http://www.shicimingju.com/book/sanguoyanyi.html
分析網站URL、文檔內容特徵
獲取網頁內容
拆分出需求內容
保存在本地

案例代碼


import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.pipeline.ConsolePipeline;
import us.codecraft.webmagic.pipeline.FilePipeline;
import us.codecraft.webmagic.pipeline.JsonFilePipeline;
import us.codecraft.webmagic.processor.PageProcessor;

public class NovelRepoPageProcessor implements PageProcessor {
    // 部分一:抓取網站的相關配置,包括編碼、抓取間隔、重試次數等
    private Site site = Site.me().setRetryTimes(3).setSleepTime(1000);

    @Override
    // process是定製爬蟲邏輯的核心接口,在這裏編寫抽取邏輯
    public void process(Page page) {
        // 部分二:定義如何抽取頁面信息,並保存下來  http://www.shicimingju.com/book/sanguoyanyi/
        page.putField("id", page.getUrl().
        		regex("http://www\\.shicimingju\\.com/book/sanguoyanyi/(\\d+)\\.html").toString());
        page.putField("name", 
            page.getHtml().xpath("//h1/text()").toString());
        if (page.getResultItems().get("name") == null) {
            //skip this page
            page.setSkip(true);
        }
        //<div class="chapter_content">
        page.putField("content", 
        		page.getHtml().xpath("//div[@class='chapter_content']/tidyText()"));

        // 部分三:從頁面發現後續的url地址來抓取
        page.addTargetRequests(page.getHtml().links().
                regex("(http://www\\.shicimingju\\.com/book/sanguoyanyi/(\\d+)\\.html)").all());
    }

    @Override
    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {

        Spider.create(new NovelRepoPageProcessor())
                //從"http://www.shicimingju.com/book/sanguoyanyi.html"開始抓
                .addUrl("http://www.shicimingju.com/book/sanguoyanyi.html")
                .addPipeline(new JsonFilePipeline("D:\\webmagic\\"))  //JSON格式保存結果到文件
                //開啓5個線程抓取
                .thread(5)
                //啓動爬蟲
                .run();
    }
}


超全面的測試IT技術課程,0元立即加入學習!有需要的朋友戳:


騰訊課堂測試技術學習地址

歡迎轉載,但未經作者同意請保留此段聲明,並在文章頁面明顯位置給出原文鏈接。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章