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

PHP 爬取中國代理伺服器網 (cnproxy.com) 代理 IP 列表

     編輯:PHP 相關知識

PHP 爬取中國代理伺服器網 (cnproxy.com) 代理 IP 列表

針對 https://www.cnproxy.com/proxy{1-10}.html 頁面結構,解析表格中經 JavaScript 混淆的 Port 號(字元對應表),提取 IP:Port 並儲存至文字檔。含分頁自動翻頁、解碼邏輯、檔案追加寫入。

完整爬蟲類別

<?php
class CnProxyCrawler {
    public $savePath = 'proxy.txt';
    private $charMap = ['z'=>3,'m'=>4,'k'=>2,'l'=>9,'d'=>0,'x'=>5,'i'=>7,'w'=>6,'q'=>8,'b'=>1];

    public function fetchPage(int $page): string {
        $url = 'https://www.cnproxy.com/proxy' . $page . '.html';
        return file_get_contents($url);
    }

    public function parse(string $html): array {
        // 正規表示式對應混淆 port 寫法:
        $pattern = '/([\d.]+)]*>document\.write\(":"([+a-z]+)\)<\/SCRIPT><\/td>\w+<\/td>[\w,]+<\/td>/is';
        preg_match_all($pattern, $html, $m);
        $proxies = [];
        foreach ($m[2] as $i => $enc) {
            $enc = str_replace('+', '', $enc);
            $port = '';
            for ($j=0; $jcharMap[$ch]) ? $this->charMap[$ch] : $ch;
            }
            $proxies[] = $m[1][$i] . ':' . $port;
        }
        return $proxies;
    }

    public function save(array $proxies): bool {
        $data = implode("\r\n", $proxies) . "\r\n";
        return file_put_contents($this->savePath, $data, FILE_APPEND | LOCK_EX) !== false;
    }

    public function run(int $start=1, int $end=10): void {
        for ($p=$start; $p<=$end; $p++) {
            echo "Fetching page $p...\n";
            $html = $this->fetchPage($p);
            $list = $this->parse($html);
            $this->save($list);
            echo "  Got " . count($list) . " proxies\n";
            sleep(2); // 禮貌延遲
        }
    }
}

// 使用
$crawler = new CnProxyCrawler();
$crawler->run(1, 10);
?>

Port 解碼邏輯說明

頁面中 Port 以字元對應表混淆:z=3, m=4, k=2, l=9, d=0, x=5, i=7, w=6, q=8, b=1。例如 +z+m → 34。爬蟲移除 + 後逐字映射還原。

法律與道德提醒

  • 爬蟲請遵守 robots.txt、限制頻率(sleep)、設定合理 User-Agent。
  • 代理 IP 可用性極低且多為透明/高匿混雜,實務上建議付費代理池或自建。
  • 部分網站禁止爬取,使用前請確認法律風險。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved