JAVA爬蟲實踐(實踐三:爬蟲架構webMagic和csdnBlog爬蟲)

來源:互聯網
上載者:User

標籤:raft   Google瀏覽器   自己   soft   使用   spider   main   標題   process   

WebMagic

WebMagic是一個簡單靈活的Java爬蟲架構。基於WebMagic,你可以快速開發出一個高效、易維護的爬蟲。

採用HttpClient可以實現定向的爬蟲,也可以自己編寫演算法邏輯來實現多線程,建立連結池,自動解析網頁代碼擷取請求連結,封裝Regex等等。

但是如果使用架構,就不再需要考慮爬蟲的邏輯,只需要專註HTML內容的解析和擷取。

引用WebMagic後寫一個爬蟲只需要編寫一個類實現PageProcessor介面,實現兩個方法。

一個WebMagic例子

 

package csdnblog;import java.io.File;import java.io.FileWriter;import java.io.IOException;import java.io.PrintWriter;import us.codecraft.webmagic.Page;import us.codecraft.webmagic.Site;import us.codecraft.webmagic.Spider;import us.codecraft.webmagic.processor.PageProcessor;public class MyPageProcessor implements PageProcessor {    @Override    public Site getSite() {        // 重試3次,抓取間隔1S        return Site.me().setRetryTimes(3).setSleepTime(1000);    }    @Override    public void process(Page page) {        page.addTargetRequests(page.getHtml().links().regex("http://blog\\.csdn\\.net/\\?&page=.*").all());            try {            // 建立新檔案            String path = "D:\\testFile\\"+getFileName(page.getUrl().toString())+".html";            PrintWriter printWriter = new PrintWriter(new FileWriter(new File(path)));            // 寫內容            printWriter.write(page.getHtml().toString());            printWriter.close();        } catch (IOException e) {            e.printStackTrace();        }    }    public static void main(String[] args) {        Spider.create(new MyPageProcessor()).addUrl("http://blog.csdn.net").thread(5).run();    }    public String getFileName(String url) {        return url.substring(20, url.length()).replace("?", "").replace("&", "");    }}

 

這個例子裡實現了一個getSite方法,用來擷取抓取網站的相關配置,包括:編碼、抓取間隔、重試次數等

還實現了一個process方法,裡面除了寫檔案的部分,就只有一個page.addTargetRequests(),它是用來為連結池添加爬蟲需要的連結,當爬蟲線程開啟後,每個線程會到連結池中取連結,當連結池為空白,爬蟲結束。

 

page.addTargetRequests(page.getHtml().links().regex("http://blog\\.csdn\\.net/\\?&page=.*").all());

 

即將所有符合"http:blog.csdn.net?&page=數字"的連結放入連結池中

 

 

例子中可以看到page.getHtml()即擷取頁面上HTML內容,在此基礎上用xpath就可以取得其中想要的資料

xpath是一種HTML標籤元素的路徑表達方式

使用Firefoxfirebug和Google瀏覽器F12都可以右鍵標籤直接複製標籤的xpath

可以採用xpath的方式擷取連結池連結

// 添加所有文章頁page.addTargetRequests(page.getHtml().xpath("//div[@class=‘blog_list_wrap‘]").links()// 限定文章列表擷取地區        .regex("http://blog\\.csdn\\.net/.*/article/details/.*")        .all());// 添加其他列表頁page.addTargetRequests(page.getHtml().xpath("//div[@class=‘page_nav‘]").links()// 限定其他列表頁擷取地區        .regex("http://blog\\.csdn\\.net.*")        .all());

使用xpath擷取頁面中想要的資料

package csdnblog;import us.codecraft.webmagic.Page;import us.codecraft.webmagic.Site;import us.codecraft.webmagic.Spider;import us.codecraft.webmagic.processor.PageProcessor;public class MyPageProcessor implements PageProcessor {    @Override    public Site getSite() {        // 重試3次,抓取間隔1S        return Site.me().setRetryTimes(3).setSleepTime(1000);    }    @Override    public void process(Page page) {        // 添加所有文章頁        page.addTargetRequests(page.getHtml().xpath("//div[@class=‘blog_list_wrap‘]").links()// 限定文章列表擷取地區                .regex("http://blog\\.csdn\\.net/.*/article/details/.*")                .all());        // 添加其他列表頁        page.addTargetRequests(page.getHtml().xpath("//div[@class=‘page_nav‘]").links()// 限定其他列表頁擷取地區                .regex("http://blog\\.csdn\\.net.*")                .all());           //如果當前頁為文章頁        if(page.getUrl().regex("http://blog\\.csdn\\.net/.*/article/details/.*").match()){            // 編號            System.out.println("編號:" + page.getUrl().regex("http://blog\\.csdn\\.net/.*/article/details/(\\d+)").get());            // 標題            System.out.println("標題:" + page.getHtml().xpath("//div[@class=‘article_title‘]//span[@class=‘link_title‘]/a/text()").get());            // 日期            System.out.println("日期" + page.getHtml().xpath("//div[@class=‘article_r‘]/span[@class=‘link_postdate‘]/text()").get());            // 標籤            System.out.println("標籤" + page.getHtml().xpath("//div[@class=‘article_l‘]/span[@class=‘link_categories‘]/a/allText()").all().toString());            // 類別            System.out.println("類別" + page.getHtml().xpath("//div[@class=‘category_r‘]/label/span/text()").all().toString());        }    }    public static void main(String[] args) {        Spider.create(new MyPageProcessor()).addUrl("http://blog.csdn.net").thread(5).run();    }}

 

JAVA爬蟲實踐(實踐三:爬蟲架構webMagic和csdnBlog爬蟲)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.