我编写了一个小的 PHP 脚本,用于使用 curl 抓取图像并将它们保存在本地。它从我的数据库中读取图像的 url,抓取它并将文件保存到文件夹中。之前在其他几个网站上进行了测试和工作,但我正在尝试一个新的网站失败了。我做了一些阅读,稍微修改了脚本,但仍然没有。
请提出要注意的事项。
$query_products = "SELECT * from product";
$products = mysql_query($query_products, $connection) or die(mysql_error());
$row_products = mysql_fetch_assoc($products);
$totalRows_products = mysql_num_rows($products);
do {
$ch = curl_init ($row_products['picture']);
$agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; rv:2.0) Gecko/20110319 Firefox/4.0');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
$rawdata = curl_exec ($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close ($ch);
if($http_status==200){
$fp = fopen("images/products/".$row_products['productcode'].".jpg", 'w');
fwrite($fp, $rawdata);
fclose($fp);
echo ' -- Downloaded <a href="'.$row_products['picture'].'" target="_blank">'.$newname.'</a> to local: <a href="images/products/'.$newname.'" target="_blank">'.$newname.'</a>';
} else {
echo ' -- Failed to download <a href="'.$row_products['picture'].'" target="_blank">'.$row_products['picture'].'</a>';
}
usleep(500);
} while ($row_products = mysql_fetch_assoc($products));