You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过PHP执行Selenium JAR文件与ChromeDriver.exe

PHP代码实现启动Selenium服务

你可以通过PHP的系统命令执行函数来实现启动Selenium服务,以下是几种常用的实现方式:

基础启动方式(分系统)

Windows环境

Windows下需要用start /B让命令后台运行,避免PHP脚本阻塞:

// 替换为实际的文件路径
$seleniumJar = 'C:/your/path/selenium-server-standalone-2.42.2.jar';
$chromeDriver = 'C:/your/path/chromedriver.exe';

$command = "start /B java -jar \"{$seleniumJar}\" -Dwebdriver.chrome.driver=\"{$chromeDriver}\"";
exec($command, $output, $returnCode);

if ($returnCode === 0) {
    echo "Selenium服务启动命令已执行";
} else {
    echo "启动失败:" . implode("\n", $output);
}

Linux/macOS环境

Linux和macOS下通过&让进程后台运行,并将输出重定向避免阻塞:

// 替换为实际的文件路径
$seleniumJar = '/your/path/selenium-server-standalone-2.42.2.jar';
$chromeDriver = '/your/path/chromedriver';

$command = "java -jar \"{$seleniumJar}\" -Dwebdriver.chrome.driver=\"{$chromeDriver}\" > /dev/null 2>&1 &";
exec($command, $output, $returnCode);

if ($returnCode === 0) {
    echo "Selenium服务启动命令已执行";
} else {
    echo "启动失败:" . implode("\n", $output);
}

精细控制进程(支持后续停止服务)

如果需要获取进程ID、读取输出或者后续终止服务,可以使用proc_open()函数:

$descriptors = [
    0 => ['pipe', 'r'], // 标准输入
    1 => ['pipe', 'w'], // 标准输出
    2 => ['pipe', 'w']  // 标准错误
];

// 替换为实际路径
$seleniumJar = 'C:/your/path/selenium-server-standalone-2.42.2.jar';
$chromeDriver = 'C:/your/path/chromedriver.exe';
$command = "java -jar \"{$seleniumJar}\" -Dwebdriver.chrome.driver=\"{$chromeDriver}\"";

$process = proc_open($command, $descriptors, $pipes);

if (is_resource($process)) {
    // 关闭管道避免阻塞
    fclose($pipes[0]);
    fclose($pipes[1]);
    fclose($pipes[2]);
    
    $status = proc_get_status($process);
    if ($status['running']) {
        echo "Selenium服务已启动,进程ID:{$status['pid']}";
        // 后续可使用 proc_terminate($process) 停止服务
    }
}

注意事项

  • 确保运行PHP的进程拥有执行Java程序、读取Selenium Jar包和ChromeDriver文件的权限
  • 如果服务器禁用了exec、shell_exec等函数,需要在php.ini中解除限制或联系服务器管理员

内容的提问来源于stack exchange,提问作者Abdul Nassar M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 22:12:23