某學習網站禁用右鍵、內容經 Base64 編碼 + URL 編碼 雙重混淆,且不在首屏 HTML 中直接輸出。本文演示如何通過抓包分析、編碼逆向、批量采集獲取完整課程內容。
Ctrl+U 查看源碼、開發者工具 Network 面板、或 view-source: 協議。test.php?wiki_id=18291。base64decode("...") 字樣,確認雙重編碼。
base64 -d 解碼後得到 URL 編碼字符串(如 %E8%AF%86%E8%AE%B0),再經 urldecode 還原中文。<?php
/**
* 批量采集課程內容
* 目標:https://www.XXX.com/test.php?wiki_id=ID
* 編碼:Base64 -> URL Encode
*/
set_time_limit(0);
ini_set('memory_limit', '256M');
$baseUrl = 'https://www.XXX.com/test.php?wiki_id=';
$startId = 18291;
$endId = 18788;
$output = __DIR__ . '/collected_content.txt';
$fp = fopen($output, 'a');
if (!$fp) die("無法打開輸出文件");
for ($id = $startId; $id <= $endId; $id++) {
$url = $baseUrl . $id;
$html = @file_get_contents($url);
if ($html === false) {
fwrite($fp, "ID $id: 請求失敗\n");
continue;
}
// 1. 提取「問題」區塊
$parts = explode('問題:', $html);
if (count($parts) < 2) continue;
$qBlock = explode('));<', $parts[1])[0]; // 截取到 base64decode 前
// 2. 提取「答案」區塊
$aParts = explode('答案:', $html);
if (count($aParts) < 2) continue;
$aBlock = $aParts[1];
// 3. 正則提取 Base64 字符串
preg_match('/base64decode\("([^"]+)"\)/', $qBlock, $qMatch);
preg_match('/base64decode\("([^"]+)"\)/', $aBlock, $aMatch);
if (empty($qMatch[1]) || empty($aMatch[1])) continue;
// 4. 解碼鏈:Base64 Decode -> URL Decode
$question = urldecode(base64_decode($qMatch[1]));
$answer = urldecode(base64_decode($aMatch[1]));
// 5. 寫入文件
fwrite($fp, "=== ID: $id ===\n");
fwrite($fp, "Q: $question\n\n");
fwrite($fp, "A: $answer\n\n\n");
// 禮貌延遲,避免觸發反爬
usleep(200000); // 0.2 秒
}
fclose($fp);
echo "采集完成,結果保存至 $output\n";
| 技術點 | 說明 | 代碼體現 |
|---|---|---|
| file_get_contents 遠程讀取 | 需開啟 php.ini allow_url_fopen=On;大并發建議換 cURL | file_get_contents($url) |
| Base64 解碼 | PHP base64_decode() 自動忽略換行/空格 | base64_decode($match[1]) |
| URL 解碼 | urldecode() 還原 %XX 為原字符,支援 UTF-8 中文 | urldecode(...) |
| 正則提取 | 非貪婪匹配 (.*?) 精確捕獲雙引號內容 | /base64decode\("([^"]+)"\)/ |
| 錯誤抑制 @ | 單次失敗不中斷整個循環 | @file_get_contents |
| 流式寫入 | fopen/fwrite/fclose 避免大內存佔用 | 文件句柄 $fp |
stream_context_create(['http'=>['header'=>"Cookie: ..."]])。⚠️ 僅供技術學習交流。采集前請閱讀目標站
robots.txt、服務條款;尊重知識產權,勿用于商業用途、大規模鏡像或競品分析。本文示例域名已脫敏為XXX.com。
通過 抓包定位接口 → 識別編碼鏈 → 正則提取 → 解碼還原 → 流式存儲 的標準化流程,配合 file_get_contents 的輕量級特性,可快速完成中小規模靜態/偽靜態站點的數據采集。核心難點不在 HTTP 請求,而在於 前端混淆邏輯的逆向分析。