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

PHP 網頁抓取與內容解析實戰:從基礎到批量採集

     編輯:PHP 相關知識

核心流程:抓取 → 合併 → 正則解析 → 結構化輸出

基礎單頁抓取示例

<?php
$url = 'https://www.php.net';
$lines = file($url);                    // 逐行讀入數組
$html  = implode('', $lines);           // 合併為完整字符串

// 正則提取 ... 內容
if (preg_match('/<head>(.*)<\/head>/is', $html, $matches)) {
    echo $matches[1];                   // $matches[1] 為捕獲組內容
}
?>

關鍵點:

  • file() 直接支援 HTTP/HTTPS URL(需 allow_url_fopen=On)
  • implode('', $lines) 無縫合併,避免換行符干擾正則
  • 正則使用 s 修飾符使 . 匹配換行,i 忽略大小寫

進階:Socket 方式抓取(繞過 allow_url_fopen 限制)

function get_content_by_socket($url, $host) {
    $fp = fsockopen($host, 80, $errno, $errstr, 10);
    if (!$fp) return false;

    $header = "GET /{$url} HTTP/1.1\r\n";
    $header .= "Host: {$host}\r\n";
    $header .= "User-Agent: Mozilla/5.0 (compatible; PHP Bot)\r\n";
    $header .= "Connection: Close\r\n\r\n";

    fwrite($fp, $header);
    $response = '';
    while (!feof($fp)) { $response .= fgets($fp, 8192); }
    fclose($fp);
    return $response;
}

批量採集與鏈接提取工具函數

以下函數集支援:索引頁批量下載、多媒體鏈接提取、目錄遍歷、去重存儲:

<?php
// 1. 批量下載索引頁
function get_index($save_file, $prefix = "index_") {
    $count = 68; $i = 1;
    @unlink($save_file);
    $fp = fopen($save_file, "a+") or die("Open failed");
    while ($i < $count) {
        $url = $prefix . $i . ".htm";
        $content = get_url($url);
        fwrite($fp, get_content_url($url, $content));
        $i++;
    }
    fclose($fp);
}

// 2. 提取頁面內所有鏈接
function get_content_url($host_url, $html) {
    $rex = '/href\s*=\s*["\']*([^"\'>\s]+)["\'>\s]*/is';
    preg_match_all($rex, $html, $r);
    $result = '';
    foreach ($r[1] as $link) {
        if (preg_match('/^(down.*\.html)$/i', $link)) {
            $result .= $host_url . $link . "\n";
        }
    }
    return $result;
}

// 3. 解析多媒體對象(示例:href + 鏈接文本)
function get_content_object($str) {
    $rex = '/href\s*=\s*["\']*([^"\'>\s]+)["\'>\s]*(.*?<\/b>)/is';
    preg_match_all($rex, $str, $m);
    if (count($m) == 3) {
        $m[2] = str_replace(['多媒體:', ' '], '', $m[2]);
        return $m[1][0] . "|--:**:--|" . $m[2][0] . "\n";
    }
    return '';
}

// 4. 通用 HTTP 獲取(支援重定向、錯誤處理)
function get_url($url) {
    if (!preg_match('/^https?:\/\/[^\/].+$/', $url)) die("Invalid URL");
    $fp = fopen($url, "r") or die("Open url failed: $url");
    $content = '';
    while ($fc = fread($fp, 8192)) $content .= $fc;
    fclose($fp);
    if (empty($content)) die("Get content failed: $url");
    return $content;
}
?>

實戰建議

  1. 編碼處理: 抓取前檢測 Content-Type charset,必要時 mb_convert_encoding() 統一轉 UTF-8
  2. 反爬應對: 設置合理 User-Agent、Referer、Cookie;控制請求頻率;使用代理 IP 池
  3. 結構化解析: 複雜頁面優先使用 DOMDocument + DOMXPath,比正則更穩健
  4. 異步並發: 大規模採集建議 Swoole/Workerman 或 GNU Parallel 多進程
  5. 合規性: 遵守 robots.txt、網站服務條款,避免法律風險

相關專題:PHP 正則表達式用法總結、PHP 網絡編程技巧總結、PHP+MySQL 數據庫操作入門教程

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