在网络爬虫、数据采集或隐私保护场景中,代理 IP 是常见需求。中国代理服务器网(cnproxy.com)提供免费代理列表,本文详细讲解如何使用 PHP 编写采集脚本,自动抓取其最新代理 IP 并保存到本地文件。
https://www.cnproxy.com/proxy{页码}.html<?php
/**
* 采集中国代理服务器网最新列表
*/
class ProxyCollector {
public $listUrl = '';
public $savePath = 'proxy.txt';
/** 生成分页 URL */
public function getListUrl($page) {
$this->listUrl = str_replace('(*)', $page, 'https://www.cnproxy.com/proxy(*).html');
return $this->listUrl;
}
/** 采集单页代理内容 */
public function fetchPage($page) {
$this->getListUrl($page);
$html = file_get_contents($this->listUrl);
if (!$html) return false;
// 正则匹配 IP 和混淆端口脚本
$pattern = '/<tr><td>([0-9.]+)<SCRIPT type=text\/javascript>document\.write\(":"([+a-z]+)\)<\/SCRIPT><\/td><td>\w+<\/td><td>[\w,]+<\/td>/is';
preg_match_all($pattern, $html, $matches);
if (empty($matches[1])) return false;
// 端口混淆映射表
$charMap = ['z','m','k','l','d','x','i','w','q','b'];
$numMap = [3,4,2,9,0,5,7,6,8,1];
$result = '';
foreach ($matches[2] as $idx => $obfuscated) {
$clean = str_replace('+', '', $obfuscated);
$port = str_replace($charMap, $numMap, $clean);
$result .= $matches[1][$idx] . ':' . $port . "\r\n";
}
$this->save($result);
return true;
}
/** 追加保存到文件 */
public function save($data) {
return file_put_contents($this->savePath, $data, FILE_APPEND);
}
/** 读取已采集数据 */
public function read() {
return file_get_contents($this->savePath);
}
}
// 使用示例:采集第 1-10 页
$collector = new ProxyCollector();
$start = 1;
$end = 10;
if (isset($_GET['a']) && $_GET['a'] === 'start') {
echo '正在发送采集请求...';
echo '<meta http-equiv="Refresh" content="3;URL=?p=1">';
} elseif (isset($_GET['p'])) {
$page = intval($_GET['p']);
if ($page > $end) {
exit('<meta http-equiv="Refresh" content="0;URL=?a=end">');
}
echo "正在请求列表 {$page} > {$end}";
if ($collector->fetchPage($page)) {
$next = $page + 1;
echo "<meta http-equiv=\"Refresh\" content=\"3;URL=?p={$next}\">";
}
} elseif (isset($_GET['a']) && $_GET['a'] === 'end') {
echo '采集完毕!';
} else {
echo '<form><input type="hidden" name="a" value="start" /><input type="submit" value="开始采集" /></form>';
}
?>
页面中端口由 JavaScript 动态写入,如 document.write(":+" + "zmk"),实际对应数字映射:
| 混淆字符 | z | m | k | l | d | x | i | w | q | b |
|---|---|---|---|---|---|---|---|---|---|---|
| 真实数字 | 3 | 4 | 2 | 9 | 0 | 5 | 7 | 6 | 8 | 1 |
脚本通过 str_replace 完成还原。
利用 URL 参数 p 控制页码,配合 meta refresh 实现分批次自动翻页,避免单次执行超时。
sleep() 或使用代理池robots.txt 与相关法律法规cURL 替代 file_get_contents,支持超时、重试、Header 伪装https://httpbin.org/ip)完整代码已在 PHP 7.4+ 环境测试通过,可直接部署使用。希望本教程能助你快速构建代理 IP 资源库。