今天無聊看在知乎上看到有人寫網絡爬蟲爬圖片( ̄▽  ̄)
傳送門:
福利 - 不過百行代碼的爬蟲爬取美女圖:https://zhuanlan.zhihu.com/p/24730075
福利 - 不過十行代碼的爬蟲爬取美女圖:https://zhuanlan.zhihu.com/p/24779556
其實這個是一個nodejs用了一百多行代碼和php只要10行代碼寫的爬蟲代碼比較( ̄▽  ̄)
不過這都不重要,重要的是,我看着無聊,自己又寫了一個花瓣的圖片爬蟲( ̄▽  ̄)( ̄▽  ̄)
注釋都在代碼里的,不多說了,直接上代碼:
<?php /** * 獲取花瓣網圖片 * @param string $mixed 查詢關鍵字或直接一個畫板id * @param int $page_limit 要查詢幾頁的,默認只查一頁 * @return void */ function getHuabanImgs($mixed, $page_limit=1){ error_reporting(0); set_time_limit(0); $board_id = 0; $keyword = ''; $max = ''; if(is_numeric($mixed)) { $board_id = $mixed; }else { $keyword = urlencode($mixed); } @mkdir('save'); for ($pageno = 1 ; $pageno <= $page_limit; $pageno ++) { /* 你喜歡用curl也行,使用這個花瓣的接口關鍵點是要在請求頭加一個 X-Requested-With:XMLHttpRequest 如果沒有這個X-Requested-With,接口返回的是一個html網頁,有的話,就是返回json */ /*$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'http://huaban.com/search/?q='.$keyword.'&ixsaam0z&page='.$pageno.'&per_page=20&wfl=1'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept:application','X-Request:JSON','X-Requested-With:XMLHttpRequest')); $response = curl_exec($ch); curl_close($ch);*/ $context = stream_context_create(array('http'=>array('method'=>'GET','header'=>"Accept:application\r\nX-Request:JSON\r\nX-Requested-With:XMLHttpRequest\r\n"))); //按畫板id查找 if($board_id>0) { $response = @file_get_contents('http://huaban.com/boards/'.$board_id.'/?&max='.$max.'&limit=20&wfl=1', 'r', $context); $arr = @json_decode($response, true); $pins = $arr['board']['pins']; } //按關鍵字查找 else { $response = @file_get_contents('http://huaban.com/search/?q='.$keyword.'&ixsaam0z&page='.$pageno.'&per_page=20&wfl=1', 'r', $context); $arr = @json_decode($response, true); $pins = $arr['pins']; } if(empty($pins)) break; foreach ((array)$pins as $key => $value) { $type = str_replace('image/', '', $value['file']['type']); if(!$type || $type=='jpeg') $type = 'jpg'; $max = $value['pin_id']; /* 花瓣的縮略圖鏈接是這個的:http://img.hb.aicdn.com/c39ac6a698b6d95b823d0840a773bdb7f2cc057216dfd-HkHx3k_fw236 而大圖的鏈接是這樣的:http://img.hb.aicdn.com/c39ac6a698b6d95b823d0840a773bdb7f2cc057216dfd-HkHx3k 可以看出,其實就是去掉后面的_fw236而已,這里使用 preg_replace 正則去掉這類后綴 */ @copy('http://img.hb.aicdn.com/' . preg_replace('/(_[\s\S]+)?/', '', $value['file']['key']), './save/'.$value['file']['id'] . '.' . $type); } } } // getHuabanImgs('向日葵', 2); getHuabanImgs('13715723', 2);
自己建個 php 文件來測試玩一下吧