業界通稱「采集器」或「爬蟲」,核心邏輯為:**發送 HTTP 請求 → 取得 HTML → 解析提取目標資料 → 儲存/重新發布**。本教學以華軍軟體園首頁為例,示範從人工分析 HTML 到編寫 PHP 采集腳本的完整流程。
https://www.onlinedown.net/index.htm<table>、<div class="stats"> 或 <span id="total"> 內。<?php
$url = 'https://www.onlinedown.net/index.htm';
$html = file_get_contents($url); // 需 allow_url_fopen=On
// 或 cURL (支援 HTTPS、Header、Cookie、Proxy)
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; PHP Collector)',
CURLOPT_TIMEOUT => 30,
]);
$html = curl_exec($ch);
curl_close($ch);
// 僅適合結構極簡、極穩定的片段
preg_match('/軟體總數:(\d+)/', $html, $m);
$total = $m[1] ?? 0;
<?php
$dom = new DOMDocument();
libxml_use_internal_errors(true); // 抑制 HTML5 非標準標籤警告
$dom->loadHTML('<?xml encoding="UTF-8"?>' . $html); // 強制 UTF-8
libxml_clear_errors();
$xpath = new DOMXPath($dom);
// 以 class/id/文字內容定位
$nodes = $xpath->query('//td[contains(text(), "軟體總數")]/following-sibling::td[1]');
if ($nodes->length > 0) {
$total = trim($nodes->item(0)->textContent);
echo "軟體總數: {$total}\n";
}
$crawler->filter('.stats > td')->text()<?php
// 存入資料庫
$pdo->prepare('INSERT INTO stats (source, total, updated_at) VALUES (?, ?, NOW())')
->execute(['onlinedown', $total]);
// Crontab 每小時執行
// 0 * * * * /usr/bin/php /path/collect.php >/dev/null 2>&1
https://target.com/robots.txt 允許路徑與爬取頻率。sleep(rand(1,3)) 避免對目標伺服器造成壓力 (DoS 風險)。采集技術本身中性,關鍵在於**合法合規的使用場景**。掌握 HTTP、HTML 解析、XPath/CSS Selector、異步佇列,能構建強大的資料管線;同時請時刻記住:技術無罪,用途有責。