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

PHP 爬蟲/採集常用工具函數庫:URL 正規化、HTML 清洗、表格轉陣列、關鍵字提取

     編輯:PHP 相關知識

函數庫總覽

針對網頁採集常見需求封裝:取得當前腳本 URL、全形轉半形數字、HTML 實體編碼/解碼、相對路徑轉絕對、超連結提取、標籤內容擷取、HTML 表格轉 CSV/二維陣列、英文單詞分詞去重。

核心函數實作

1. 取得當前腳本完整 URL

function get_php_url() {
    if (!empty($_SERVER['REQUEST_URI'])) {
        return $_SERVER['REQUEST_URI'];
    }
    $script = $_SERVER['PHP_SELF'];
    return empty($_SERVER['QUERY_STRING']) ? $script : $script . '?' . $_SERVER['QUERY_STRING'];
}

2. 全形數字轉半形

function GetAlabNum($str) {
    $full = ['0','1','2','3','4','5','6','7','8','9'];
    $half = '0123456789';
    $str = str_replace($full, str_split($half), $str);
    return preg_replace('/[^0-9\.]|^0+/', '', $str) ?: '0';
}

3. HTML 實體編碼/解碼

function Text2Html($txt) {
    $txt = str_replace(' ', ' ', $txt);
    $txt = str_replace('<', '<', $txt);
    $txt = str_replace('>', '>', $txt);
    return preg_replace('/[\r\n]+/', "
\r\n", $txt); } function ClearHtml($str) { return str_replace(['<','>'], ['<','>'], $str); }

4. 相對路徑轉絕對 URL

function relative_to_absolute($content, $baseUrl) {
    if (preg_match('/^(https?|ftp):\/\//', $baseUrl, $m)) $proto = $m[0];
    $host = preg_replace('/^(https?|ftp|news):\/\//', '', $baseUrl);
    $host = preg_replace('/\/.*/', '', $host);
    if (!$host) return $content;
    if (isset($proto)) {
        $content = preg_replace('/href="\//', 'href="' . $proto . $host . '/', $content);
        $content = preg_replace('/src="\//', 'src="' . $proto . $host . '/', $content);
    }
    return $content;
}

5. 提取所有超連結

function get_all_url($html) {
    preg_match_all('/]*href=["\']?([^"\'\s>]+)["\']?[^>]*>([^<]+)<\/a>/i', $html, $m);
    return ['url' => $m[1], 'name' => $m[2]];
}

6. 擷取指定標籤間內容

function get_tag_data($str, $start, $end) {
    if (!$start || !$end) return null;
    $tmp = explode($start, $str, 2);
    if (count($tmp) < 2) return null;
    $tmp = explode($end, $tmp[1], 2);
    return $tmp[0];
}

7. HTML 表格轉 CSV 陣列(逐列)

function get_tr_array($tableHtml) {
    $table = preg_replace('/<\/td>\s*]*>/i', '{td}', $table);
    $table = str_replace('', '{tr}', $table);
    $table = preg_replace('/<[\/!]*?[^<>]*?>/si', '', $table);
    $table = preg_replace('/(\r\n)\s+/', '', $table);
    $table = str_replace([' ',' '], '', $table);
    $rows = explode('{tr}', $table);
    array_pop($rows);
    return $rows;
}

8. HTML 表格轉二維陣列(逐儲存格)

function get_td_array($tableHtml) {
    $table = preg_replace('/]*>.*<\/thead>/si', '', $tableHtml);
    $table = preg_replace('/]*>|<\/tbody>/si', '', $table);
    $table = preg_replace('/]*>.*<\/tfoot>/si', '', $table);
    $table = str_replace('', '{tr}', $table);
    $table = str_replace('', '{td}', $table);
    $table = preg_replace('/<[\/!]*?[^<>]*?>/si', '', $table);
    $table = preg_replace('/(\r\n)\s+/', '', $table);
    $table = str_replace([' ',' '], '', $table);
    $rows = explode('{tr}', $table);
    array_pop($rows);
    $result = [];
    foreach ($rows as $row) {
        $cells = explode('{td}', $row);
        array_pop($cells);
        $result[] = $cells;
    }
    return $result;
}

9. 英文單詞分詞去重排序

function split_en_str($str, $distinct = true) {
    preg_match_all('/([a-zA-Z]+)/', $str, $m);
    $words = $m[1];
    if ($distinct) $words = array_unique($words);
    sort($words);
    return $words;
}

實務應用建議

  • 編碼處理:採集前先偵測網頁編碼(mb_detect_encoding 或 HTTP Header),統一轉 UTF-8 再處理。
  • 反爬蟲:設定 User-Agent、Cookie、Referer、間隔請求、使用 Proxy 池。
  • 結構化解析:複雜頁面優先用 DOMDocument + XPath,正則僅作輔助。
  • 法律合規:遵守 robots.txt、網站服務條款、個資法(GDPR/PDPA),勿過度請求造成服務阻斷。

現代替代方案

  • Goutte:Guzzle + DOMCrawler + CSS 選擇器,適合中小型採集。
  • Symfony Panther:支援 JavaScript 渲染(Chrome/Firefox headless),處理 SPA 頁面。
  • Scrapy (Python):大型分散式爬蟲框架,生態成熟。

此函數庫適合輕量級、無 JavaScript 渲染需求的採集任務,理解其原理有助於除錯與客製化。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved