萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 使用 Requests 庫串接百度圖片 API 打造瀑布流美女圖牆

專案目標

利用百度圖片頻道非公開 API,透過 PHP Requests 庫 獲取圖片資料,前端採用瀑布流 (Masonry/Waterfall) 展示,打造簡單的圖片牆 Demo。

API 逆向分析

觀察百度圖片「美女」頻道網路請求:

  • 請求 URL:https://image.baidu.com/data/imgs
  • 關鍵參數:
    • col=美女 (頻道)
    • tag=全部 (標籤)
    • pn=起始索引 (分頁偏移)
    • rn=數量 (每頁筆數)
  • 回傳 JSON:{imgs: [{shareUrl: '...'}, ...]}

PHP 後端程式碼 (api.php)

<?php
require_once './Requests/library/Requests.php';
Requests::register_autoloader();

$page     = max(1, intval($_GET['page'] ?? 1));
$pageSize = 10;
$offset   = ($page - 1) * $pageSize;

$options = ['headers' => ['Host' => 'image.baidu.com']];
$url = sprintf(
    'https://image.baidu.com/data/imgs?sort=0&pn=%d&rn=%d&col=%s&tag=%s&tag3=&p=channel&from=1',
    $offset, $pageSize,
    urlencode('美女'), urlencode('全部')
);

$response = Requests::get($url, $options);
header('Content-Type: application/json; charset=utf-8');
echo $response->body;

前端瀑布流 (index.html)

<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>Beauty Wall</title>
<style>
#wall { column-count: 4; column-gap: 10px; padding: 10px; }
.item { break-inside: avoid; margin-bottom: 10px; }
.item img { width: 100%; height: auto; display: block; border-radius: 4px; box-shadow: 0 2px 4px rgba(0,0,0,.1); }
@media (max-width: 800px) { #wall { column-count: 2; } }
@media (max-width: 500px) { #wall { column-count: 1; } }
</style></head><body>
<div id="wall"></div>
<script>
const wall = document.getElementById('wall');
let page = 1, loading = false;
async function load() {
  if (loading) return; loading = true;
  const res = await fetch('api.php?page=' + page);
  const data = await res.json();
  if (!data.imgs?.length) return;
  data.imgs.forEach(img => {
    const div = document.createElement('div');
    div.className = 'item';
    div.innerHTML = '<img src="' + img.shareUrl + '" loading="lazy">';
    wall.appendChild(div);
  });
  page++; loading = false;
}
window.addEventListener('scroll', () => {
  if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 500) load();
});
load();
</script></body></html>

專案結構

pretty/
├── index.html      # 前端頁面
├── api.php         # PHP 代理 API
└── Requests/       # Requests 庫 (composer require rmccue/requests)

注意事項與優化

  • 法律合規:百度圖片 API 非官方開放,僅供學習研究;生產環境請使用合法授權圖庫 (Unsplash、Pexels API 等)。
  • 反爬蟲:需模擬完整 Header (User-Agent, Referer)、處理 Cookie、IP 輪換。
  • 快取:API 回應可快取至 Redis,減少對上游請求。
  • 圖片代理:防盜鏈時需 PHP 代理圖片或簽名 URL。
  • Requests 庫:現代專案建議改用 GuzzleHttp 或 Http\Client (PSR-18)。

完整原始碼:GitHub Repository

copyright © 萬盛學電腦網 all rights reserved