使用php實現爬蟲程序 套取網站的圖片實例

<?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電影網中電影列表的部分圖片   經過以上的爬取程序 咱們就能夠爬取任何網站的圖片了 php

相關文章
相關標籤/搜索