百度移動端圖片搜尋提供 JSON 介面,可透過 PHP 串接獲取圖片連結。本文示範基本串接與分頁顯示,並說明法律風險與替代方案。
<?php
// 參數處理
$page = isset($_GET['p']) ? max(1, intval($_GET['p'])) : 1;
$pn = ($page - 1) * 20; // 百度 pn 參數:起始索引
// 構造請求 URL (關鍵字:美女)
$keyword = '美女';
$url = 'https://m.baidu.com/img?' . http_build_query([
'tn' => 'bdjsonliulan',
'pu' => 'sz@1320_2001',
'bd_page_type' => 1,
'tag1' => $keyword,
'realword' => $keyword,
'word' => $keyword,
'pn' => $pn,
'rn' => 20,
]);
// 發送請求
$ctx = stream_context_create([
'http' => [
'timeout' => 10,
'header' => "User-Agent: Mozilla/5.0 (Linux; Android 10) AppleWebKit/537.36\r\n" .
"Referer: https://m.baidu.com/\r\n"
]
]);
$json = @file_get_contents($url, false, $ctx);
if ($json === false) {
die('請求失敗,請稍後再試');
}
$data = json_decode($json, true);
if (empty($data['data'])) {
die('無圖片資料或介面變更');
}
// 輸出 HTML
header('Content-Type: text/html; charset=utf-8');
?>
百度圖片搜尋 -
- 第 頁
| 參數 | 說明 |
|---|---|
| tn | 固定值 bdjsonliulan,指定 JSON 介面 |
| word / realword / tag1 | 搜尋關鍵字 (需 URL 編碼) |
| pn | 起始索引,第 1 頁為 0,第 2 頁為 20,以此類推 |
| rn | 每頁數量,通常 20 |
| User-Agent | 必須模擬瀏覽器,否則可能返回 403/空資料 |
robots.txt,IP 易被封禁。本文僅供技術研究學習,請勿用於商業或非法用途。尊重知識產權,從合法獲取圖片開始。