php实现自动填表
PHP 实现自动填表的方法
使用 cURL 模拟表单提交
通过 cURL 可以模拟浏览器行为,自动向目标表单提交数据。以下是一个基本示例:
$url = 'https://example.com/form-handler.php';
$data = [
'username' => 'testuser',
'password' => 'testpass',
'submit' => 'Submit'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($ch);
curl_close($ch);
使用 DOMDocument 解析和填充 HTML 表单
对于需要先解析 HTML 表单结构的场景:
$html = file_get_contents('https://example.com/form-page.html');
$dom = new DOMDocument();
@$dom->loadHTML($html);
$form = $dom->getElementsByTagName('form')->item(0);
// 获取表单字段并填充值
$inputs = $form->getElementsByTagName('input');
foreach ($inputs as $input) {
$name = $input->getAttribute('name');
if ($name && isset($data[$name])) {
$input->setAttribute('value', $data[$name]);
}
}
// 提交处理后的表单
$updatedHtml = $dom->saveHTML();
使用 PHP 的 file_get_contents 方法
对于简单的 GET 请求表单提交:
$url = 'https://example.com/form-handler.php?' . http_build_query($data);
$response = file_get_contents($url);
处理验证码和复杂表单
对于包含验证码或动态 token 的表单:
- 使用 OCR 库处理简单验证码
- 通过会话保持获取动态 token
- 可能需要配合 JavaScript 解析工具
// 示例:保持会话处理
$cookieFile = tempnam(sys_get_temp_dir(), 'cookie');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://example.com/login');
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$loginPage = curl_exec($ch);
// 提取表单中的 token
preg_match('/name="token" value="(.*?)"/', $loginPage, $matches);
$token = $matches[1] ?? '';
// 使用 token 提交表单
$data['token'] = $token;
curl_setopt($ch, CURLOPT_URL, 'https://example.com/login-handler');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$response = curl_exec($ch);
curl_close($ch);
使用第三方库
可以考虑使用以下专门处理表单的 PHP 库:
- Goutte:简单的 Web Scraper
- PHPBrowser:配合 Mink 使用
- Symfony DomCrawler:强大的 HTML 解析器
安装 Goutte 示例:
composer require fabpot/goutte
使用示例:
use Goutte\Client;
$client = new Client();
$crawler = $client->request('GET', 'https://example.com/form-page');
$form = $crawler->selectButton('Submit')->form();
$response = $client->submit($form, [
'username' => 'testuser',
'password' => 'testpass'
]);
处理 AJAX 表单
对于动态加载的 AJAX 表单:

- 分析网络请求找出真正的 API 端点
- 直接模拟这些 AJAX 请求
- 可能需要设置特定的 HTTP 头
$url = 'https://example.com/api/form-submit';
$headers = [
'X-Requested-With: XMLHttpRequest',
'Content-Type: application/json'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
注意事项
- 确保遵守目标网站的服务条款
- 处理可能的重定向和错误响应
- 考虑请求间隔避免被封禁
- 对于复杂场景可能需要结合多种技术
以上方法可以根据具体需求组合使用,实现不同复杂度的自动填表功能。






