<?php //去采集a67 圖片 網站鏈接 http://www.xiamov.com/list/1/p.2 你也可以采集其他網站的圖片 //創建鏈接 dedecms--a67
//設置執行不超時 set_time_limit(0);
//fsockopen() 函數 第一個參數是指主機 第二個參數指的是端口號 一般我們默認為80端口 第三個參數是錯誤編號 第四個參數是返回錯誤的字符串 第五個參數指的是鏈接時長 我上面寫的是30秒 如果30秒沒有鏈接到對方主機 則會返回鏈接失敗 $conn=fsockopen("www.xiamov.com",80,$errno,$errstr,30); if(!$conn){ die("鏈接失敗"); } //說話 協議 $httpstr="GET /list/1/p.2 HTTP/1.1\r\n"; $httpstr.="Host: www.xiamov.com\r\n"; $httpstr.="Connection: Close\r\n\r\n"; //發送http請求 對方就應該有回應 fwrite($conn,$httpstr,strlen($httpstr)); //看看a67 網站會送的是什么東西 $res=""; while(!feof($conn)){ $res.=fread($conn,1024); } fclose($conn); //file_put_contents("D:/1.txt", $res); //echo $res;
//我要找到該頁面的圖片資源 img src //<img alt="邪惡小分隊下載" title="邪惡小分隊下載" src="http://img.xiamov.com/vod/2016-07/578e2cc52da30.jpg">
$reg1='/<img alt="[^"]*" title="[^"]*" src="([^"]*)"/i'; //這個是匹配上面的<img 的正則表達式 [^"]* 這個表示的是 只要不是“ 就不斷匹配 這個很常用 可以學習 preg_match_all($reg1,$res,$arr1); //把$arr1[1]遍歷 並取出各個圖片的uri foreach($arr1[1] as $imgurl){ //echo"<br/>".$imgurl; $imguri=str_replace("http://img.xiamov.com","",$imgurl); //echo"<br/>".$imguri; //再次發出請求 要圖片 注意 這里的主機發生變化了 主機變化為img.xiamov.com
$conn=fsockopen("img.xiamov.com",80,$errno,$errstr,30);
//組織httpstr
$httpstr="GET $imguri HTTP/1.1\r\n";
$httpstr.="Host: img.xiamov.com\r\n";
$httpstr.="Connection: Close\r\n\r\n";
//發出請求 img
fwrite($conn,$httpstr,strlen($httpstr));
$res2="";
while(!feof($conn)){
$res2.=fread($conn,1024);
}
fclose($conn);
//看看$res2是什么
//file_put_contents("D:/1.txt", $res2);
//exit();
//我們把圖片的數據從$res2截取出來 保存成圖片
$pos=strpos($res2,"\r\n\r\n");
$imgres=substr($res2,$pos+4); //后面加的數字很重要 這個數字4 是本人不斷測試才得到的
$fileinfo=pathinfo($imguri);
file_put_contents("./myimages/".$fileinfo['basename'], $imgres);
//die;
sleep(2); //我們可以使用sleep函數 來延遲發送請求
}
die("成功取回圖片");
以上是采取A67電影網中電影列表的部分圖片 通過以上的爬取程序 我們就可以爬取任何網站的圖片了
