1. 程式人生 > >八、學習爬蟲框架WebMagic(四)---使用webmagic+Selenium爬取小說

八、學習爬蟲框架WebMagic(四)---使用webmagic+Selenium爬取小說

一、案例說明
  本案例以爬取某小說網站某本小說為例(PS:避免商業問題,這裡不提小說網站名)

二、先期準備
  關於 webmagic+Selenium 的相關依賴,參見 七、學習爬蟲框架WebMagic(三)—webmagic+Selenium爬取動態頁面

三、構建專案

(一)專案分析
  在某小說網站找到一本小說的列表,如下:
在這裡插入圖片描述

  根據頁面,然後分析網頁原始碼,可知在這個頁面中,下一頁的網址每篇文章的網址會給出。然後,根據查詢原始碼可知,下一頁的網址每篇文章的網址是通過 JS 動態載入的,所以框架選型就是 Webmagic+Selenium。

  根據 Webmagic 框架的特點,只要我們定好爬取規則,它會一直爬取下去直到結束。每頁和每篇文章的URL,可通過爬取每頁URL抽取出來。比如我爬取第一頁,我就會找到第二頁的URL和第一頁中所有文章的URL,爬取第二頁就會找到第三頁URL。以此類推,我們只要找到每頁URL,即可找到該頁所有文章URL和下一頁URL。所以,我制定的爬取業務邏輯是:

  找出頁面中的所有URL(連結),然後根據翻頁和每篇文章的URL的規則,設計正則表示式,對符合條件的URL進行爬取。

注意:Webmagic 框架會自動幫我們去重。比如:我們在首頁會找到末頁和第二頁的URL,這是我們第一次訪問到末頁的URL。在我們遍歷第二頁的時候,還會找到第三頁的URL,以此類推,最後我們還會找到末頁URL一次,這樣我們會爬取末頁URL兩次。但是,Webmagic 框架會記錄已經爬取過的網頁,再次遇到末頁URL的時候,會將它剔除出去,不再爬取。

(二)程式碼

1、爬取業務規則

package org.pc.exercise;

import
org.pc.webmagic.update.SeleniumDownloader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.CollectionUtils; 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.Html; import java.util.List; import java.util.regex.Pattern; /** * @author 鹹魚 * @date 2018/12/31 10:13 */ public class NovelPageProcessorInBiQuGe implements PageProcessor { private final Logger LOGGER = LoggerFactory.getLogger(this.getClass()); /** * 每頁URL正則 */ private static final String CHAPTER_URL = "http://m.biquyun.com/1_1559_\\d+/"; /** * 每篇文章URL正則 */ private static final String CONTENT_URL = "http://m.biquyun.com/wapbook/1559_\\d+\\.html"; private Pattern chapterPattern = Pattern.compile(CHAPTER_URL); private Pattern contentPattern = Pattern.compile(CONTENT_URL); private Site site; /** * 目標URL */ private static final String NOVEL_URL = "http://m.biquyun.com/1_1559_1/"; @Override public void process(Page page) { String url = page.getUrl().toString(); if (chapterPattern.matcher(url).find()){ chapterProcess(page); } else if (contentPattern.matcher(url).find()){ contentProcess(page); } else { LOGGER.info("該URL:" + url + "不是目標路徑"); } } /** * 取出每章節中章節名,小說的內容 * @param page */ private void contentProcess(Page page) { Html pageHtml = page.getHtml(); String bookName = pageHtml.xpath("//h1[@id='chaptertitle']/text()").toString(); String content = pageHtml.xpath("//div[@id='novelcontent']/p/text()").toString(); page.putField("bookName", bookName); page.putField("content", content); } /** * 取出小說章節列表中所有章節地址,並放進爬取佇列 */ private void chapterProcess(Page page) { Html pageHtml = page.getHtml(); //取出所有連結 List<String> links = pageHtml.links().all(); if (!CollectionUtils.isEmpty(links)){ links.forEach((link) -> { //只有每頁URL和每篇文章的URL才會進行爬取 if (chapterPattern.matcher(link).find() || contentPattern.matcher(link).find()) { page.addTargetRequest(link); } }); } else { LOGGER.warn("沒有取到小說章節地址!"); } } @Override public Site getSite() { if (site == null) { site = Site.me().setDomain("http://m.biquyun.com/") .setSleepTime(1000); } return site; } public static void main(String[] args) { Spider.create(new NovelPageProcessorInBiQuGe()) .addUrl(NOVEL_URL) //自定義Pipeline,需設定檔案輸出地址 .addPipeline(new NovelFilePipeline("E:\\demo\\novel")) //修改後的SeleniumDownloader .setDownloader(new SeleniumDownloader("E:\\demo\\crawler\\chromedriver.exe")) .thread(5) .run(); } }

2、處理規則(輸出到檔案)

package org.pc.exercise;

import com.sun.xml.internal.stream.writers.UTF8OutputStreamWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;
import us.codecraft.webmagic.utils.FilePersistentBase;

import java.io.*;

/**
 * @author 鹹魚
 * @date 2018/12/31 11:02
 */
public class NovelFilePipeline extends FilePersistentBase implements Pipeline {

    private Logger logger = LoggerFactory.getLogger(getClass());

    public NovelFilePipeline() {
        setPath("E:\\demo\\novel");
    }

    public NovelFilePipeline(String path) {
        setPath(path);
    }

    @Override
    public void process(ResultItems resultItems, Task task) {
        String bookName = resultItems.get("bookName");
        String rawContent = resultItems.get("content");
        if (StringUtils.isEmpty(bookName) || StringUtils.isEmpty(rawContent)){
            return;
        }
        //將空格替換成換行
        String content = rawContent.replace("    ", "\r\n\t");
        String path = this.path + PATH_SEPERATOR + bookName + ".txt";
        PrintWriter writer = null;
        try {
            writer = new PrintWriter(new UTF8OutputStreamWriter(new FileOutputStream(getFile(path))));
            writer.print(content);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}