原理與上一篇無需寫任何規則,智能一鍵采集網頁內容-php采集源碼類似,本代碼只采集圖片,限制為jpg圖片了,其他的跳過,需要其他格式的自行修改。與前者最大的區別是,可以指定外部地址,這一點主要是考慮b2b網站,如慧聰等,他們的詳情域名并非當前域名,而對于此類域名只抓起圖片,不繼續抓其下的鏈接,否則會把整個站的圖片都下載下來,不是我想要的。圖片地址沒有做判斷,可以是站內的,站外的,都下載了。另外相對地址的圖片跳過了,如./、../等地址格式。
show_msg('開始采集'.$url.'中的圖片'); $d=file_get_contents($url); if(!$d){ $ch = curl_init(); $timeout = 5; curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11'); //在需要用戶檢測的網頁里需要增加下面兩行 //curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); //curl_setopt($ch, CURLOPT_USERPWD, US_NAME.":".US_PWD); $d = curl_exec($ch); curl_close($ch); } preg_match('/<body.*?>([.\s\S]*?)<\/body>/i',$d,$x);//獲取body $body=$x[1];//body //采集內容 preg_match_all('/src="(.*?)"|src=\'(.*?)\'|src=(.*?) /i',$body,$img); $imgs=$img[1]; foreach ($imgs as $key => $value) { if($value){ if(!strstr($value,'.jpg')) continue; $start=strpos($value,'//'); if($start>6 || $start===false){ $value=$this->url.ltrim($value,'/'); }elseif($start===0){ $value='http:'.$value; } $ex=M('Imgurl')->where('pic="'.$value.'"')->find(); if(!$ex){ //下載圖片 if($this->savepath){ $_img=file_get_contents($value); if($_img){ $_ex=explode('.',$value); $count=count($_ex); $_ex=$_ex[$count-1]; $_fname=date('YmdHis').'_'.rand(100000,999999).'.'.$_ex; file_put_contents($this->savepath.$_fname, $_img); //這里可以判斷一下圖片大小,不合適的再刪除,如果能下載之前判斷就好了 } } if(strpos($value,'//')===0){ $value='http:'.$value; } //保存圖片數據 $imgt=array( 'sid'=>$this->sid, 'pic'=>$value ); M('Imgurl')->add($imgt); show_msg($value.'采集完成'); } } } //保存頁面數據 $t=array( 'sid'=>$this->sid, 'url'=>$url, 'ed'=>1 ); M('Imgpage')->where('url="'.$url.'"')->save($t); show_msg($url.'采集完成'); //如果當前鏈接是外部地址 不再繼續爬取url if(strstr($url,strstr($this->url,'//'))){ //采集鏈接 preg_match_all('/a.*?href=(\"|\')(.*?)(\"|\')/', $body, $y); $urls=$y[2]; foreach ($urls as $key => $value) { // http://www.x.com https://www.x.com //www.x.com /x.html ./x.html ../x.html 還可能是外部鏈接 http://www.bbbb.com https://www.cccc.com if($value){ $start=strpos($value,'//'); if($start===false){ if($value=='#' || strstr($value,'./') || strstr($value,'../') || strstr($value,'tel') || strstr($value,'javascript')) continue;//跳過 空地址、相對地址、電話、js $value=$this->url.ltrim($value,'/'); }else{ if($start<7){ //http:// https:// 可能是內部鏈接 也可能是外部鏈接 if(!strstr($value,strstr($this->url,'//')) && !strstr($value,strstr($this->out,'/'))){ continue;//跳過外部鏈接 } }else{ $value=$this->url.ltrim($value,'/'); } } $ex=M('Imgpage')->where('url="'.$value.'"')->find(); if(!$ex){ //新增 $t=array( 'sid'=>$this->sid, 'url'=>$value, 'ed'=>0 ); M('Imgpage')->add($t); } } } }
程序運行效果:
© 致遠 2020-11-07,原創內容,轉載請注明出錯:無需寫任何規則,全自動采集整站圖片