1. 程式人生 > >WebMagic 抓取圖片並保存至本地

WebMagic 抓取圖片並保存至本地

入門實例 end 中文 creat 並保存 網絡 進入 nec sel

1.近期接觸到java 爬蟲,開源的爬蟲框架有很多,其中WebMagic 是國產的,文檔也是中文的,網上資料很多,便於學習,功能強大,可以在很短時間內實現一個簡單的網絡爬蟲。具體可參考官網 http://webmagic.io/docs/zh/。今天參考官網和網上資料實現了抓取網頁圖片,並保存在本地簡單入門實例,日後再做進一步深入探討。在實現過程中參考了一些網上資料,主要是理解原理和工作方式。

2.分析網頁結構。我們抓的是http://www.win4000.com/ 這個網站的圖片,我們進到高清壁紙圖庫

技術分享圖片

找到要抓的圖片,按F12進入調試模式

技術分享圖片

我們要抓的圖片都在 class 為clearfix 的ui標簽下的li標簽內的a標簽內,a標簽的連接地址為圖片的詳情,計入詳情頁找到圖片的具體地址和標題的地址

技術分享圖片

技術分享圖片

其實每個圖片的詳情頁進去有很多張圖片,我們目前只抓了第一張,其余圖片的抓取,後面繼續完善,本次只是了解基本實現方式。具體篩選圖片鏈接和標題請查看代碼。可參考官網selecttable 和Jsoup章節。下面開始寫代碼實現。

3.利用webMagic構建一個簡單的網絡爬蟲很簡單,首先添加webMagic依賴,主要是兩個核心jar包

<dependency>
     <groupId>us.codecraft</groupId>
    <artifactId>webmagic-core</artifactId>
     <
version>0.7.3</version> </dependency> <dependency> <groupId>us.codecraft</groupId> <artifactId>webmagic-extension</artifactId> <version>0.7.3</version> </dependency>

其中webmagic核心部分,只包含爬蟲基本模塊和基本抽取器。webmagic的擴展模塊,提供一些更方便的編寫爬蟲的工具。另外還有其他擴展模塊,具體請查看百度百科介紹https://baike.baidu.com/item/WebMagic/22066484

WebMagic 使用slf4j-log4j12作為slf4j的實現.如果你自己定制了slf4j的實現,請在項目中去掉此依賴。
<exclusions>
    <exclusion>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
    </exclusion>
</exclusions>

如果沒有使用Maven,自行下載Jar包後添加至lib即可。

具體實現如下,實現PageProcessor即可。

public class myImageProcess implements PageProcessor{
    //頁面URL的正則表達式
    //.是匹配所有的字符,//.表示只匹配一個,//.?同理
    
    private static String REGEX_PAGE_URL = "http://www\\.win4000\\.com/zt/gaoqing_\\w+.html";
    //爬取的頁數
    public static int PAGE_SIZE = 10;
    //下載張數
    public static int INDEX_PHOTO =1;
    
    public void process(Page page) {
          List<String> SpidertURL = new ArrayList<String>();
          
            for (int i = 2; i < PAGE_SIZE; i++){//添加到目標url中
                SpidertURL.add("http://www.win4000.com/zt/gaoqing_" + i + ".html");
            }
            //添加url到請求中
            page.addTargetRequests(SpidertURL);
            //是圖片列表頁面
            System.out.println(page.getUrl());
            if (page.getUrl().regex(REGEX_PAGE_URL).match()) {
                //獲得所有詳情頁的連接
                //page.getHtml().xpath("//a[@class=\"title\"]").links().all();
                List<String> detailURL = page.getHtml().xpath("//ul[@class=‘clearfix‘]/li/a").links().all();
                for (String str:detailURL){//輸出所有連接
                    System.out.println(str);
                }
                page.addTargetRequests(detailURL);
            } else {//詳情頁
                    String picURL = page.getHtml().xpath("//div[@class=‘pic-meinv‘]/a").css("img", "src").toString();
                    System.out.println(picURL);
                    String picname = page.getHtml().xpath("//div[@class=‘ptitle‘]/h1/text()").toString();
                    System.out.println(picname);
                    try {
                        /**
                         * String 圖片地址
                         * String 圖片名稱
                         * String 保存路徑
                         */
                        if(picURL !=null){
                            DownloadUtil.download( picURL, picname + ".jpg", "E:\\image2\\");
                            System.out.println("第"+(INDEX_PHOTO++)+"張");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
           }
        
    }

    public Site getSite() {
        return Site.me();
    }
    
    
    public static void main(String [] args){
        Date stdate = new Date();
        System.out.println("開始時間:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(stdate));
        Spider.create(new myImageProcess()).addUrl("http://www.win4000.com/zt/gaoqing_1.html")
        .thread(5)
        .run();
        Date edDate = new Date();
        System.out.println("結束時間:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(edDate));
        System.out.println("共耗時"+(edDate.getTime()-stdate.getTime())/1000/60+"分鐘");
    }
}

圖片下載

public class DownloadUtil {
    public static void download(String urlStr,String filename,String savePath) throws IOException {
         
        URL url = new URL(urlStr);
        //打開url連接
        URLConnection connection = url.openConnection();
        //請求超時時間
        connection.setConnectTimeout(5000);
        //輸入流
        InputStream in = connection.getInputStream();
        //緩沖數據
        byte [] bytes = new byte[1024];
        //數據長度
        int len;
        //文件
        File file = new File(savePath);
        if(!file.exists())
            file.mkdirs();
 
        OutputStream out  = new FileOutputStream(file.getPath()+"\\"+filename);
        //先讀到bytes中
        while ((len=in.read(bytes))!=-1){
            //再從bytes中寫入文件
            out.write(bytes,0,len);
        }
        //關閉IO
        out.close();
        in.close();
 
    }

}

直接運行即可執行上面的main方法。至於還能用來抓什麽,可自行體會。

5.抓取結果。

技術分享圖片

技術分享圖片

繼續學習,以後可以用來抓點好東西!!!!

暫時寫到這裏,後面繼續完善。

WebMagic 抓取圖片並保存至本地