使用原生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
儲存,就算完成了