程式設計師的福利:使用WebCollector爬取某美女網站上的圖片
阿新 • • 發佈:2019-02-07
程式設計師的福利:使用WebCollector爬取某美女網站上的圖片
0x00 需求
某網站,有海量美女圖片,裡面預設是按美女的英文名字(A-Z)排序的。估算了一下,至少也得有3000+位美女照片,每位的照片數目從幾十張到幾百張不等。瀏覽了幾天,才瀏覽了很少的一部分。心想,用瀏覽器瀏覽這麼慢,效率那個低啊,這麼多照片什麼時候才能欣賞完。於是需求就來了:如何爬取這個網站上的美女圖片呢?
0x01 工具
筆者選擇的爬蟲框架是WebCollector。
WebCollector是一個無須配置、便於二次開發的JAVA爬蟲框架(核心),它提供精簡的的API,只需少量程式碼即可實現一個功能強大的爬蟲。WebCollector-Hadoop是WebCollector的Hadoop版本,支援分散式爬取。
相關文件和下載連線在這裡:http://www.oschina.net/p/webcollector/edit
筆者使用的版本是2.24
如何安裝和配置,這裡不詳解了,請查閱相關文件。
0x02 Code
查閱該網站網頁的元素,確認圖片的URL為http://[網站名稱]/jav/[美女英文名]/[main index]/[美女英文名]-[sub index].jpg
閒話少說,Talk is easy, show me the code:
public class Main extends BreadthCrawler{ public Main(String crawlPath, boolean autoParse) throws Exception { super(crawlPath, autoParse); } @Override public void visit(Page page, CrawlDatums craw) { /*不處理非jpg的網頁/檔案*/ if(!Pattern.matches(".*jpg", page.getUrl())){ return; } //http://[網站名稱]/jav/[美女英文名]/[main index]/[美女英文名]-[sub index].jpg String strUrl = page.getUrl(); String[] strPart = strUrl.split("/"); if (strPart.length < 7) { return; } String strMainIndex = strPart[5]; String strPicNameURL = strPart[6]; int nLabel = strPicNameURL.lastIndexOf("-"); if (nLabel < 0) { return; } String strBeautiName = strPicNameURL.substring(0, nLabel); String strSubIndex = strPicNameURL.substring(nLabel+1, strPicNameURL.length()); String strPicPath = "Download\\"+strBeautiName+ "\\" +strBeautiName + "_" + strMainIndex + "-" + strSubIndex; //儲存路徑格式Download\[美女名字]\[美女名字]-[主編號]-[次編號].jpg /*將圖片內容儲存到檔案,page.getContent()獲取的是檔案的byte陣列*/ try { FileUtils.writeFileWithParent(strPicPath, page.getContent()); System.out.println(page.getUrl()); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) throws Exception { Main crawler = new Main("MyCollector", true); try { crawler.addSeed("http://www.[網站網址].com"); String strReg = "http://www.[網站網址]/jav/*.*"; crawler.addRegex(strReg); crawler.setThreads(50); crawler.start(8); } catch(java.io.IOException e){ } } }
最後程式運行了很久(按天算),但資料量也不小,可憐的硬碟:
0x03總結
雖然耗費了很長時間才把很多圖片爬取下來,但仔細檢查發現,有些圖片是沒有爬取下來的,通過日誌分析發現,爬蟲在進行URL請求時,有些頁面的URL是請求失敗的。這些URL對應於其他網站,而這些網站是被封掉的。程式寫的也很匆忙,讀者若有什麼新的爬蟲技術,歡迎分享和指導。