對於爬蟲的好奇好像由來已久,一直在研究python的爬蟲,今天得空研究研究php的爬蟲
index.php
1 <?php 2 header("Content-Type:text/html;charset=utf-8"); 3 if(isset($_GET['img']) and !empty($_GET['img'])){ 4 include 'getimg.php'; 5 $img=new GetImg(); 6 $img->set('start_page',90000); 7 $img->set('end_page',90010); 8 $img->start_getimg(); 9 }else{ 10 echo "<a href='./index.php?img=1'>開始</a>"; 11 }
getimg.php
1 <?php 2 /** 3 * 957796988@qq.com 4 */ 5 ini_set('implicit_flush',1); //為一個配置選項設置值 6 ob_implicit_flush(1); //打開絕對刷送 7 ob_end_clean(); //清空(擦除)緩沖區並關閉輸出緩沖 8 date_default_timezone_set('PRC'); //初始化時區 9 set_time_limit(0); //設置腳本最大執行時間 10 11 class GetImg{ 12 13 private $start_page=90010; //開始頁數 14 private $end_page=91000; //結束頁數 15 private $url='images'; //命名文件夾 16 17 public function set($key,$val){ 18 19 $this->$key=$val; 20 } 21 22 /*CURL*/ 23 private function curl_get_con($url,$https=true,$method="get",$data=null){ 24 $ch=curl_init(); 25 26 curl_setopt($ch,CURLOPT_URL,$url); 27 28 curl_setopt($ch,CURLOPT_HEADER,false); 29 30 curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); 31 32 if($https){ 33 curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false); 34 35 curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false); 36 } 37 38 if($method=="post"){ 39 curl_setopt($ch,CURLOPT_POST,true); 40 41 curl_setopt($ch,CURLOPT_POSTFIELDS,$data); 42 } 43 44 $str=curl_exec($ch); 45 46 curl_close($ch); 47 48 return $str; 49 } 50 51 /*保存圖片方法*/ 52 private function save_img($url,$dir,$i){ 53 //創建目錄 54 if(!is_dir($dir)){ 55 mkdir($dir,777); 56 } 57 //獲取內容 58 $res=file_get_contents($url); 59 //命名文件 60 $file_name=$dir.'/'.$i.'_'.date('Ymd_His').'.jpg'; 61 //重寫 62 file_put_contents($file_name,$res); 63 return $file_name; 64 } 65 66 67 68 /*獲取方法*/ 69 public function start_getimg(){ 70 71 echo "<style>table{ border-collapse:collapse }tr{border:1px solid #ccc}</style> 72 <table width='1000' border='0' cellpadding='5' cellspacing='5' ><tr width='100'><td colspan='2'>爬蟲已運行:請查看".$this->url."文件夾</td></tr>"; 73 for($i=$this->start_page+1;$i<=$this->end_page;$i++){ 74 //爬 地址 75 $url="https://www.bbb290.com/htm/pic2/".$i.".htm"; 76 //開啟CURL 獲取到內容 77 $result=$this->curl_get_con($url); 78 //使用正則匹配內容中的 圖片 79 preg_match_all("/https:\/\/img.*jpg/U",$result,$a); 80 81 $a=$a[0]; 82 83 echo "<tr><td>正在捕捉".$i."。</td><td>"; 84 85 if(empty($a)){ 86 echo "<br /> ----".$i."為空。</td></tr>"; 87 continue; 88 } 89 90 foreach ($a as $value){ 91 //保存圖片 92 $file_name=$this->save_img($value,$this->url,$i); 93 echo "<img src='".$file_name."' width='100' height='100' />"; 94 } 95 if($i==$this->end_page){ 96 echo "<br /> ----".$i."捕捉結束。</td></tr>"; 97 echo "<br />全部捕捉結束。"; 98 break; 99 } 100 echo "<br /> ----".$i."捕捉結束。</td></tr>"; 101 } 102 } 103 }
網址貌似被河蟹了~~