首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 爬取百度收錄、快照與熱搜關鍵字完整程式碼集

     編輯:PHP 相關知識

PHP 百度 SEO 數據採集工具箱

本文整理三個實用的 PHP 爬蟲範例:查詢網站百度收錄量、最新快照日期、以及百度熱搜榜關鍵字。所有範例均採用 file_get_contents 或 cURL 獲取頁面,配合正則表達式或 SimpleXML 解析。

一、查詢百度收錄量 (site 語法)

<?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>

三、抓取百度熱搜榜 (RSS/XML 介面)

<?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
    ...
)
*/
?>

四、進階:cURL 版通用抓取函式 (解決 file_get_contents 限制)

許多主機禁用 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());
}
?>

五、反爬蟲與合規建議

  • 頻率控制:單 IP 每分鐘 ≤ 10 次請求,使用 sleep() 或 Token Bucket 演算法限流。
  • 快取機制:收錄量、熱搜榜數據變化緩慢,建議快取 1-6 小時 (Redis/Memcached/檔案)。
  • 官方 API 優先:百度站長平台提供 站長工具 API 可合法獲取收錄、抓取頻次、索引量等數據。
  • 法律風險:大規模爬蟲可能違反《計算機信息網路國際聯網管理暫行規定》及百度《服務條款》,商業用途請申請授權。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved