引言
环境准备
在开始之前,请确保您的计算机上已安装以下软件:
- PHP
- Apache/Nginx
- MySQL(可选,用于存储图片)
1. 准备工作
1.1 安装PHP库
# 在Linux系统中,可以使用以下命令安装
sudo apt-get install php-curl php-fileinfo
# 在Windows系统中,可以在PHP安装过程中手动安装
1.2 创建PHP脚本
<?php
// 定义图片URL
$imageUrl = 'http://example.com/image.jpg';
// 创建cURL会话
$ch = curl_init($imageUrl);
// 设置cURL选项
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
// 执行cURL会话
$response = curl_exec($ch);
// 关闭cURL会话
curl_close($ch);
// 检查响应状态
if (curl_errno($ch)) {
// 输出错误信息
echo 'cURL Error: ' . curl_error($ch);
} else {
// 检查HTTP状态码
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200) {
// 保存图片
$imagePath = 'downloaded_image.jpg';
file_put_contents($imagePath, $response);
echo 'Image downloaded successfully: ' . $imagePath;
} else {
// 输出HTTP状态码
echo 'HTTP Status Code: ' . curl_getinfo($ch, CURLINFO_HTTP_CODE);
}
}
?>
2. 高效爬取图片
2.1 并发下载
使用pthreads
库实现并发下载,可以显著提高下载速度。
<?php
require_once 'pthreads.php';
class ImageDownloader extends Thread {
private $imageUrl;
public function __construct($imageUrl) {
$this->imageUrl = $imageUrl;
}
public function run() {
// ... (此处省略下载代码)
}
}
// 获取图片URL列表
$imageUrls = [
'http://example.com/image1.jpg',
'http://example.com/image2.jpg',
// ... (更多图片URL)
];
// 创建并启动线程
foreach ($imageUrls as $imageUrl) {
$downloader = new ImageDownloader($imageUrl);
$downloader->start();
}
?>
2.2 使用队列
当下载任务较多时,可以使用队列来管理下载任务,避免服务器资源耗尽。
<?php
// ... (此处省略引入pthreads库的代码)
class Queue {
private $queue = [];
public function add($url) {
$this->queue[] = $url;
}
public function get() {
return array_shift($this->queue);
}
public function isEmpty() {
return empty($this->queue);
}
}
// 创建队列
$queue = new Queue();
// 将图片URL添加到队列
foreach ($imageUrls as $imageUrl) {
$queue->add($imageUrl);
}
// 创建并启动线程
while (!$queue->isEmpty()) {
$url = $queue->get();
$downloader = new ImageDownloader($url);
$downloader->start();
}
?>