天天看點

基于Crawler4j + jsoup實作爬蟲

爬蟲架構分類

1. 分布式爬蟲

Nutch

2. Java單機爬蟲

Crawler4j、WebMagic、WebCollector

3. 非Java單機爬蟲

Scrapy

開發思路

根據業務需求選擇合适的爬蟲架構

根據網站規則及業務需求抽取資料,儲存到中間庫

資料清洗/格式化,儲存到目标庫

基于Crawler4j + jsoup實作爬蟲

用Crawler4j建構多線程的web爬蟲來抓取頁面内容。Crawler4j的使用分為兩個步驟:

(1) 實作一個繼承自WebCrawler的爬蟲類

需要覆寫兩個主要方法:

shouldVisit:這個方法決定了要抓取的URL及其内容。

visit:當URL下載下傳完成會調用這個方法。使用jsoup解析HTML,可以采用jQuery選擇器的文法。

(2) 通過CrawController調用實作的爬蟲類。

指定抓取的種子(seed)、中間資料存儲的檔案夾、并發線程的數目等資訊,實作控制器類。 

示例代碼

pom.xml中依賴包設定

<dependency>
	<groupId>edu.uci.ics</groupId>
	<artifactId>crawler4j</artifactId>
	<version>4.2</version>
</dependency>
<dependency>
	<groupId>org.jsoup</groupId>
	<artifactId>jsoup</artifactId>
	<version>1.10.1</version>
</dependency>
           

代碼

(1) 爬蟲類

public class MyCrawler extends WebCrawler {
 
    private final static Pattern FILTERS = Pattern.compile(".*(\\.(css|js|gif|jpg"
                                                           + "|png|mp3|mp3|zip|gz))$");
 
    /**
     * This method receives two parameters. The first parameter is the page
     * in which we have discovered this new url and the second parameter is
     * the new url. You should implement this function to specify whether
     * the given url should be crawled or not (based on your crawling logic).
     * In this example, we are instructing the crawler to ignore urls that
     * have css, js, git, ... extensions and to only accept urls that start
     * with "http://www.ics.uci.edu/". In this case, we didn't need the
     * referringPage parameter to make the decision.
     */
     @Override
     public boolean shouldVisit(Page referringPage, WebURL url) {
         String href = url.getURL().toLowerCase();
         return !FILTERS.matcher(href).matches()
                && href.startsWith("http://www.ics.uci.edu/");
     }
 
     /**
      * This function is called when a page is fetched and ready
      * to be processed by your program.
      */
     @Override
     public void visit(Page page) {
         String url = page.getWebURL().getURL();
         System.out.println("URL: " + url);
 
         if (page.getParseData() instanceof HtmlParseData) {
             HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
             String text = htmlParseData.getText();
             String html = htmlParseData.getHtml();
             Set<WebURL> links = htmlParseData.getOutgoingUrls();
 
             System.out.println("Text length: " + text.length());
             System.out.println("Html length: " + html.length());
             System.out.println("Number of outgoing links: " + links.size());
         }
    }
}
           

(2) Controller調用

public class Controller {
    public static void main(String[] args) throws Exception {
        String crawlStorageFolder = "/data/crawl/root";
        int numberOfCrawlers = 7;
 
        CrawlConfig config = new CrawlConfig();
        config.setCrawlStorageFolder(crawlStorageFolder);
 
        /*
         * Instantiate the controller for this crawl.
         */
        PageFetcher pageFetcher = new PageFetcher(config);
        RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
        RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
        CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
 
        /*
         * For each crawl, you need to add some seed urls. These are the first
         * URLs that are fetched and then the crawler starts following links
         * which are found in these pages
         */
        controller.addSeed("http://www.ics.uci.edu/~lopes/");
        controller.addSeed("http://www.ics.uci.edu/~welling/");
        controller.addSeed("http://www.ics.uci.edu/");
 
        /*
         * Start the crawl. This is a blocking operation, meaning that your code
         * will reach the line after this only when crawling is finished.
         */
        controller.start(MyCrawler.class, numberOfCrawlers);
    }
}
           

繼續閱讀