本文提供一個完整的 PHP 腳本,用於批量下載百度貼吧相冊中的原圖。腳本會解析相冊頁面返回的 JSON 數據,提取圖片 ID,拼接原圖 URL 並保存到本地。
<?php
set_time_limit(0); // 取消執行時間限制
// 配置參數
$tbname = 'mugen'; // 貼吧名稱
$tid = '2124904411'; // 相冊 ID
$savePath = 'R:/images/'; // 本地存儲根目錄
$galleryUrl = sprintf(
'https://tieba.baidu.com/photo/bw/picture/guide?kw=%s&tid=%s',
urlencode($tbname), $tid
);
$fileDir = $savePath . $tid;
if (!is_dir($fileDir)) {
mkdir($fileDir, 0755, true);
}
// 獲取相冊 JSON 數據
$json = file_get_contents($galleryUrl);
$data = json_decode($json, true);
if (!isset($data['data']['pic_list'])) {
die('無法解析相冊數據,可能結構已變更或需要登錄 Cookie');
}
foreach ($data['data']['pic_list'] as $pic) {
$picId = $pic['img']['original']['id'];
$imgUrl = "https://imgsrc.baidu.com/forum/pic/item/{$picId}.jpg";
$saveFile = $fileDir . "/{$picId}.jpg";
// 若文件已存在則跳過,支援斷點續傳
if (file_exists($saveFile)) {
echo "已存在:{$picId}.jpg\n";
continue;
}
$imgData = @file_get_contents($imgUrl);
if ($imgData === false) {
echo "下載失敗:{$imgUrl}\n";
continue;
}
file_put_contents($saveFile, $imgData);
echo "已保存:{$picId}.jpg\n";
usleep(200000); // 禮貌延遲 0.2 秒,避免觸發反爬蟲
}
echo "任務完成。\n";
json_decode 即可獲取圖片列表。https://imgsrc.baidu.com/forum/pic/item/{id}.jpg,其中 id 為 32 位十六進制字符串。@ 抑制警告,配合 === false 判斷下載失敗,避免腳本中斷。usleep 延遲,必要時需攜帶 Cookie(登錄態)或使用代理 IP 池。curl 分塊寫入,避免 file_get_contents 佔用過多內存。爬蟲僅供學習研究,請遵守《網絡安全法》及百度《服務協議》,勿大規模高頻請求,尊重版權與用戶隱私。