PHP抓取網頁圖片的執行個體

來源:互聯網
上載者:User

標籤:php抓取圖片

PHP抓取網頁圖片的執行個體

<?php/**  * 抓取網站上的圖片到本地 * PS: 如果網頁中的圖片路徑不是絕對路徑,就無法抓取  */  set_time_limit(0);//抓取不受時間限制    $URL=‘http://image.baidu.com/‘;//任意網址    get_pic($URL);    function get_pic($pic_url) {      //擷取圖片二進位流      $data=CurlGet($pic_url);      /*利用Regex得到圖片連結*/      $pattern_src = ‘/<[img|IMG].*?src=[\‘|\"](.*?(?:[\.gif|\.jpg]))[\‘|\"].*?[\/]?>/‘;      $num = preg_match_all($pattern_src, $data, $match_src);      $arr_src=$match_src[1];//獲得圖片數組     print_r($arr_src);     get_name($arr_src);            echo "<br>finished!!!";      return 0;  }    /*得到圖片類型,並將其儲存到與該檔案同一目錄*/  function get_name($pic_arr) {      //圖片類型      $pattern_type = ‘/(\.(jpg|bmp|jpeg|gif|png))/‘;                foreach($pic_arr as $pic_item){//迴圈取出每幅圖的地址          $num = preg_match_all($pattern_type, $pic_item, $match_type);  if($num){        $pic_name = get_unique().$match_type[1][0];//改時微秒時間戳記命名          //以流的形式儲存圖片          $write_fd = @fopen(‘./getpic/‘.$pic_name,"wb");                  @fwrite($write_fd, CurlGet($pic_item));          @fclose($write_fd);          echo "[OK]..!"; }     }      return 0;  }    //通過微秒時間獲得唯一ID  function get_unique(){      list($msec, $sec) = explode(" ",microtime());      return $sec.intval($msec*1000000);  }    //抓取網頁內容  function CurlGet($url){       $url=str_replace(‘&amp;‘,‘&‘,$url);      $curl = curl_init();      curl_setopt($curl, CURLOPT_URL, $url);      curl_setopt($curl, CURLOPT_HEADER, false);            //curl_setopt($curl, CURLOPT_REFERER,$url);      curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; SeaPort/1.2; Windows NT 5.1; SV1; InfoPath.2)");      curl_setopt($curl, CURLOPT_COOKIEJAR, ‘cookie.txt‘);      curl_setopt($curl, CURLOPT_COOKIEFILE, ‘cookie.txt‘);      curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);      curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);      $values = curl_exec($curl);      curl_close($curl);      return $values;  }  ?>


本文出自 “開心編程_永無止境” 部落格,請務必保留此出處http://happyliu.blog.51cto.com/501986/1585346

PHP抓取網頁圖片的執行個體

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.