本文整理三個實用的 PHP 爬蟲範例:查詢網站百度收錄量、最新快照日期、以及百度熱搜榜關鍵字。所有範例均採用 file_get_contents 或 cURL 獲取頁面,配合正則表達式或 SimpleXML 解析。
<?php
/**
* 取得百度收錄數量
* @param string $domain 域名 (如 'example.com')
* @return int 收錄數量
*/
function getBaiduIndexCount($domain) {
$url = 'https://www.baidu.com/s?wd=site%3A' . urlencode($domain);
$html = @file_get_contents($url);
if ($html === false) return 0;
// 百度頁面為 GB2312,若 PHP 為 UTF-8 需轉碼或直接用 GB2312 正則
// 模式:找到相關結果數約 1,234 個
if (preg_match('/找到相關結果數約?([\d,]+)個/', $html, $m)) {
return (int)str_replace(',', '', $m[1]);
}
return 0;
}
// 使用
echo getBaiduIndexCount('www.hzhuti.com'); // 輸出數字
?>
<?php
$domain = 'www.hzhuti.com';
$siteUrl = 'https://www.baidu.com/s?wd=site%3A';
$allUrl = $siteUrl . urlencode($domain);
$todayUrl = $allUrl . '&lm=1'; // lm=1 限制 24 小時
$patterns = [
'total' => '/找到相關結果數約?([\d,]+)個/',
'snapshot' => '/<span class="g">([^<]+)<\/span>/',
'date' => '/\d{4}-\d{1,2}-\d{1,2}/'
];
$htmlAll = @file_get_contents($allUrl);
$htmlToday = @file_get_contents($todayUrl);
$total = $today = 0;
$snapshot = '暫無快照';
if ($htmlAll) {
preg_match($patterns['total'], $htmlAll, $m);
$total = $m ? (int)str_replace(',', '', $m[1]) : 0;
preg_match($patterns['snapshot'], $htmlAll, $m);
if ($m && preg_match($patterns['date'], $m[1], $d)) $snapshot = $d[0];
}
if ($htmlToday) {
preg_match($patterns['total'], $htmlToday, $m);
$today = $m ? (int)str_replace(',', '', $m[1]) : 0;
}
?>
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>百度 SEO 查詢</title></head>
<body>
<table border="1" cellpadding="5">
<tr><th>日期</th><th>總收錄</th><th>今日收錄</th><th>快照日期</th></tr>
<tr>
<td><?php echo date('m月d日 H:i'); ?></td>
<td><?php echo number_format($total); ?></td>
<td><?php echo number_format($today); ?></td>
<td><?php echo $snapshot; ?></td>
</tr>
</table>
<p>總收錄:<a href="<?php echo $allUrl; ?>" target="_blank"><?php echo number_format($total); ?></a></p>
<p>今日收錄:<a href="<?php echo $todayUrl; ?>" target="_blank"><?php echo number_format($today); ?></a></p>
<p>快照日期:<?php echo $snapshot; ?></p>
</body></html>
<?php
/**
* 取得百度熱搜關鍵字陣列
* @return array 關鍵字列表
*/
function getBaiduHotKeywords() {
// 百度熱搜 RSS 介面 (可能需調整參數)
$rssUrl = 'https://top.baidu.com/rss_xml.php?p=top10';
$xmlContent = @file_get_contents($rssUrl);
if ($xmlContent === false) return [];
// 修正 XML 實體與編碼宣告
$xmlContent = str_replace('&', '&', $xmlContent);
$xmlContent = '' . $xmlContent;
$xml = simplexml_load_string($xmlContent);
if (!$xml) return [];
$keywords = [];
// 解析表格列 (依實際 XML 結構調整 XPath)
foreach ($xml->xpath('//tr') as $row) {
$link = $row->xpath('td/a');
if ($link) {
$keywords[] = trim((string)$link[0]);
}
}
return $keywords;
}
$hotWords = getBaiduHotKeywords();
print_r($hotWords);
/* 輸出範例:
Array
(
[0] => 關鍵字1
[1] => 關鍵字2
...
)
*/
?>
許多主機禁用 allow_url_fopen,或需偽裝 User-Agent、處理 Cookie、HTTPS 憑證。通用 cURL 封裝:
<?php
function fetchUrl($url, $options = []) {
$defaults = [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36',
CURLOPT_TIMEOUT => 15,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
CURLOPT_SSL_VERIFYPEER => false, // 僅開發測試用,生產請配置 CA 憑證
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_ENCODING => 'gzip,deflate', // 自動解壓
];
$ch = curl_init();
curl_setopt_array($ch, $defaults + $options);
$data = curl_exec($ch);
$err = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($err) throw new Exception("cURL Error: $err");
if ($info['http_code'] >= 400) throw new Exception("HTTP {$info['http_code']}");
return $data;
}
// 使用範例:替換上方所有 file_get_contents
try {
$html = fetchUrl('https://www.baidu.com/s?wd=site%3Aexample.com');
// ... 解析 ...
} catch (Exception $e) {
error_log($e->getMessage());
}
?>
sleep() 或 Token Bucket 演算法限流。