類設計目標
- 輸入種子 URL,按層級廣度優先抓取。
- 自動補全相對路徑、過濾非目標擴展名、去重。
- MySQL 記錄已訪問 URL,避免重複抓取。
核心代碼 (現代化重寫)
<?php
class Spider {
private PDO $db;
private string $baseUrl;
private int $maxDepth;
private array $visited = [];
public function __construct(PDO $db, string $startUrl, int $maxDepth = 2) {
$this->db = $db;
$this->baseUrl = $this->normalizeUrl($startUrl);
$this->maxDepth = $maxDepth;
$this->initDb();
}
private function initDb(): void {
$this->db->exec("CREATE TABLE IF NOT EXISTS visited (
url VARCHAR(500) PRIMARY KEY,
depth TINYINT UNSIGNED NOT NULL,
crawled_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
}
// URL 規範化:補全 scheme、去除尾部斜杠、片段
private function normalizeUrl(string $url): string {
$url = trim($url);
if (!preg_match('~^https?://~i', $url)) $url = 'https://' . $url;
$parts = parse_url($url);
$path = rtrim($parts['path'] ?? '/', '/');
return $parts['scheme'] . '://' . $parts['host'] . ($parts['port'] ? ':' . $parts['port'] : '') . ($path ?: '/');
}
// 判斷是否已抓取
private function isVisited(string $url): bool {
$stmt = $this->db->prepare('SELECT 1 FROM visited WHERE url = ?');
$stmt->execute([$url]);
return (bool)$stmt->fetchColumn();
}
private function markVisited(string $url, int $depth): void {
$stmt = $this->db->prepare('INSERT IGNORE INTO visited (url, depth) VALUES (?, ?)');
$stmt->execute([$url, $depth]);
}
// 從 HTML 提取所有 鏈接
private function extractLinks(string $html, string $base): array {
$dom = new DOMDocument();
@$dom->loadHTML($html); // 抑制 HTML5 解析警告
$links = [];
foreach ($dom->getElementsByTagName('a') as $a) {
$href = $a->getAttribute('href');
if ($href === '' || $href[0] === '#') continue; // 錨點/空
$abs = $this->resolveUrl($href, $base);
if ($abs) $links[] = $abs;
}
return $links;
}
// 相對轉絕對
private function resolveUrl(string $href, string $base): ?string {
if (preg_match('~^https?://~i', $href)) return $this->normalizeUrl($href);
$baseParts = parse_url($base);
$basePath = rtrim(dirname($baseParts['path']), '/') . '/';
$abs = $baseParts['scheme'] . '://' . $baseParts['host'] . ($baseParts['port'] ? ':' . $baseParts['port'] : '') . $basePath . ltrim($href, '/');
return $this->normalizeUrl($abs);
}
// 遞歸抓取
public function crawl(string $url = '', int $depth = 0): void {
$url = $url ?: $this->baseUrl;
if ($depth > $this->maxDepth || $this->isVisited($url)) return;
$this->markVisited($url, $depth);
echo "[$depth] Crawling: $url\n";
$html = @file_get_contents($url);
if ($html === false) return;
// 此處可解析內容、存儲數據...
$links = $this->extractLinks($html, $url);
foreach ($links as $link) {
$this->crawl($link, $depth + 1);
usleep(100000); // 禮貌延遲 100ms
}
}
}
// 使用
$pdo = new PDO('mysql:host=localhost;dbname=spider;charset=utf8mb4', 'user', 'pass');
$spider = new Spider($pdo, 'https://example.com', 2);
$spider->crawl();
?>
生產級建議
- 遵守
robots.txt、設置 User-Agent、限制請求頻率。
- 使用 Guzzle + PSR-18 替代
file_get_contents,支援並發、重試、中間件。
- 大規模爬蟲採用 **Scrapy (Python)**、**Colly (Go)** 或 **Swoole/ReactPHP** 異步協程。
- 去重用 **Bloom Filter** 或 **Redis Set** 替代 MySQL 主鍵。
- 解析用 **DOMDocument/XPath** 或 **CSS Selector (symfony/dom-crawler)**。