ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

使用php preg_match_all&cURL从多个页面中抓取/下载图像

2019-06-26 12:29:04  阅读:235  来源: 互联网

标签:php curl image preg-match-all


所以我试图从另一个网站抓取一些图像,问题是每个图像都在不同的页面上

IE:id / 1,id / 2,id / 3等等

到目前为止,我有下面的代码,可以从使用下面给出的单个URL获取图像:

$returned_content = get_data('http://somedomain.com/id/1/');

但需要让上面的一行成为一个数组(我猜)所以它将从第1页抓取图像,然后继续抓住第2页上的下一个图像,然后是第3页等等

function get_data($url){
 $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; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
 $data = curl_exec($ch);
  curl_close($ch);
 return $data;
}

$returned_content = get_data('http://somedomain.com/id/1/');

if (preg_match_all("~http://somedomain.com/images/(.*?)\.jpg~i", $returned_content, $matches)) {

$src = 0;
      foreach ($matches[1] as $key) {

if(++$src > 1) break;

          $out = $key;
      }

      $file = 'http://somedomain.com/images/' . $out . '.jpg';


$dir = 'photos'; 

$imgurl = get_data($file);

file_put_contents($dir . '/' . $out . '.jpg', $imgurl);

echo  'done';
}

一如既往,所有的帮助都表示赞赏,并提前感谢.

解决方法:

这非常令人困惑,因为听起来你只对每页保存一个图像感兴趣.但是代码使得它看起来像是在尝试保存每个页面上的每个图像.所以我完全有可能完全误解了……但是这里有.

在每个页面上循环并不困难:

$i = 1;
$l = 101;

while ($i < $l) {
    $html = get_data('http://somedomain.com/id/'.$i.'/');
    getImages($html);
    $i += 1;
}

以下假设您尝试保存该特定页面上的所有图像:

function getImages($html) {
    $matches = array();
    $regex = '~http://somedomain.com/images/(.*?)\.jpg~i';
    preg_match_all($regex, $html, $matches);
    foreach ($matches[1] as $img) {
        saveImg($img);
    }
}

function saveImg($name) {
    $url = 'http://somedomain.com/images/'.$name.'.jpg';
    $data = get_data($url);
    file_put_contents('photos/'.$name.'.jpg', $data);
}

标签:php,curl,image,preg-match-all
来源: https://codeday.me/bug/20190626/1293812.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有