輸入網址,抓取頁面所有 <img> 標籤的 src 屬性,下載圖片儲存至本地。
jpg|bmp|png|gif 四種格式的 src。fopen/fwrite 二進位寫入檔案。function CurlGet($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
$values = curl_exec($ch);
curl_close($ch);
return $values;
}
function get_pic($pic_url){
$data = CurlGet($pic_url);
$patterns = array(
'/<img.*?src=["\'](.*?\.jpg)["\'].*?>/i',
'/<img.*?src=["\'](.*?\.bmp)["\'].*?>/i',
'/<img.*?src=["\'](.*?\.png)["\'].*?>/i',
'/<img.*?src=["\'](.*?\.gif)["\'].*?>/i'
);
foreach($patterns as $p){
preg_match_all($p, $data, $m);
foreach($m[1] as $img){
$filename = basename($img);
$fp = fopen($filename, 'wb');
fwrite($fp, CurlGet($img));
fclose($fp);
echo "下載:$img <br/>";
}
}
// 第二輪:處理相對路徑
foreach($patterns as $p){
preg_match_all($p, $data, $m);
foreach($m[1] as $img){
$full = $pic_url . $img;
$filename = basename($img);
$fp = fopen($filename, 'wb');
fwrite($fp, CurlGet($full));
fclose($fp);
}
}
}
簡單表單輸入網址,送出執行 get_pic()。
DOMDocument 或 QueryList 等解析器。robots.txt 與版權。