php实现自动填表
PHP 实现自动填表的方法
使用 PHP 实现自动填表通常涉及模拟表单提交或与网页交互。以下是几种常见的方法:
cURL 模拟表单提交
通过 cURL 库模拟 HTTP 请求,适用于 POST 或 GET 表单提交。
$url = 'https://example.com/form-submit';
$data = ['username' => 'test', 'password' => '123456'];
$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);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
Guzzle HTTP 客户端

Guzzle 是一个流行的 PHP HTTP 客户端,简化了 HTTP 请求的发送。
require 'vendor/autoload.php';
$client = new GuzzleHttp\Client();
$response = $client->post('https://example.com/form-submit', [
'form_params' => [
'username' => 'test',
'password' => '123456'
]
]);
echo $response->getBody();
使用 DOM 操作自动填写表单
对于需要与网页交互的场景,可以使用 PHP 的 DOM 操作库。

$html = file_get_contents('https://example.com/form-page');
$dom = new DOMDocument();
@$dom->loadHTML($html);
$form = $dom->getElementsByTagName('form')->item(0);
$inputs = $form->getElementsByTagName('input');
foreach ($inputs as $input) {
if ($input->getAttribute('name') == 'username') {
$input->setAttribute('value', 'test');
}
}
$newHtml = $dom->saveHTML();
echo $newHtml;
Selenium WebDriver
对于复杂的网页交互,可以使用 Selenium WebDriver 进行自动化测试。
require 'vendor/autoload.php';
$host = 'http://localhost:4444/wd/hub';
$driver = RemoteWebDriver::create($host, DesiredCapabilities::chrome());
$driver->get('https://example.com/form-page');
$driver->findElement(WebDriverBy::name('username'))->sendKeys('test');
$driver->findElement(WebDriverBy::name('password'))->sendKeys('123456');
$driver->findElement(WebDriverBy::id('submit'))->click();
$driver->quit();
注意事项
- 确保目标网站允许自动化操作,避免违反服务条款。
- 处理验证码或动态加载的内容可能需要额外工具。
- 对于需要登录的表单,可能需要维护会话或 Cookie。
以上方法可以根据具体需求选择,简单的表单提交使用 cURL 或 Guzzle,复杂的交互使用 Selenium。






