使用原生php爬取图片并保存到本地

通过一个简单的例子复习一下几个php函数的用法

用到的函数或知识点

  • curl 发送网络请求
  • preg_match 正则匹配

代码

$url     = 'http://desk.zol.com.cn/bizhi/7386_91671_2.html';
$headers = [
    'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
];
$ch      = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     //将curl_exec()获取的信息以字符串返回,而不是直接输出。
curl_setopt($ch, CURLOPT_HEADER, $headers);
$output = curl_exec($ch);
curl_close($ch);
$str = mb_convert_encoding($output, 'utf-8', 'gb2312');
//或$str = iconv('gb2312//IGNORE', 'utf-8', $output);

preg_match('!<img id="bigImg" src="(?<src>http.*\.(?<ext>jpg|png))".*>!', $str, $m);
file_put_contents('./meinv.' . $m['ext'], file_get_contents($m['src']));

效果

解释

curl 发送请求

在php中建立curl连接的步骤一般为:初始化,设置选项,执行操作,释放连接。

$ch = curl_init();
curl_setopt($ch, CURLOPT, $opt);
$out = curl_exec($ch);
curl_close();

常用的CURLOPT设置,更多参考文档 http://php.net/manual/zh/function.curl-setopt.php

CURLOPT_URL, string //设置url必须
CURLOPT_HEADER, array //设置请求header
CURLOPT_RETURNTRANSFER, bool //为true时,以字符串返回响应,不包含header
CURLOPT_SSL_VERIFYPEER, bool //为false时,不验证https证书,用于请求https的url
CURLOPT_POST, int //为1时配合CURLOPT_POSTFIELDS使用post请求,默认使用get
CURLOPT_POSTFIELDS, array //post数据数组

直接输出$output发现乱码,通过查看源码发现网页使用的是gb2312编码,用mb_convert_encoding或者iconv转换成utf-8编码输出。

preg_match 正则匹配

通过查看源码发现我们需要的图片标签为<img id="bigImg" src="https://desk-fd.zol-img.com.cn/t_s960x600c5/g5/M00/0A/03/ChMkJ1wY5y-IfHR_AALCDzHE3wwAAt3AgOmA_IAAsIn642.jpg" width="960" height="600">

正则表达式

<img id="bigImg" src="(?<src>http.*\.(?<ext>jpg|png))".*>

.*匹配所有,(?<name>)使用分组可以方便的使用$match['name']取到想要的部分

最后$match['src']拿到了图片的真实url,通过file_put_contents保存,就算完成了

猜你喜欢

转载自www.cnblogs.com/luke44/p/php-craw-picture-and-save-to-local.html