如何在使用createSeleniumClient运行Symfony Panther时禁用GUI
解决Symfony Panther + Selenium Grid 无法隐藏GUI的问题
问题根源
当使用createSeleniumClient连接Selenium Grid时,PANTHER_NO_HEADLESS环境变量不再生效,且createSeleniumClient的第四个本地驱动启动参数也无法被远程Grid节点识别。要给远程Chrome实例设置无头模式,必须通过ChromeOptions将启动参数注入到DesiredCapabilities中。
修复步骤
修改你的BrowserScrape.php代码,通过ChromeOptions配置无头模式及其他浏览器参数,再将其附加到DesiredCapabilities:
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Symfony\Component\Panther\Client; use Facebook\WebDriver\Remote\DesiredCapabilities; use Facebook\WebDriver\Chrome\ChromeOptions; // 新增引入 class BrowserScrape extends Command { protected $signature = 'browser:scrape'; protected $description = 'Command description'; private Client $client; public function __construct() { parent::__construct(); // 配置Chrome启动参数 $chromeOptions = new ChromeOptions(); $chromeOptions->addArguments([ '--disable-popup-blocking', '--disable-application-cache', '--disable-web-security', '--ignore-certificate-errors', '--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36', '--window-size=1200,1100', '--headless=new', // 推荐使用Chrome新无头模式,旧版--headless在新版Chrome中可能失效 '--disable-gpu', ]); $capabilities = [ "os" => "Windows", "os_version" => "11", "browser" => "Chrome", "browser_version" => "latest", "name" => "Test", "build" => "Build 1.0", "browserstack.debug" => true, "browserstack.console" => "info", "browserstack.networkLogs" => true, "disableCorsRestrictions" => true, "wsLocalSupport" => true, "geoLocation" => "GB" ]; $caps = DesiredCapabilities::chrome(); // 将ChromeOptions添加到capabilities $caps->setCapability(ChromeOptions::CAPABILITY, $chromeOptions); foreach ($capabilities as $key => $value) { $caps->setCapability($key, $value); } $this->client = Client::createSeleniumClient( 'http://localhost:'.config('app.selenium_grid_port').'/wd/hub', $caps, null // 移除第四个参数,远程Grid不使用本地驱动选项 ); } private function getInput() { $words = $this->ask('>>'); $this->info($words); } public function handle() { $this->client->get('https://www.imdb.com/search/name/?birth_monthday=12-10'); $crawler = $this->client->getCrawler(); // 处理Cookie弹窗,增加存在性判断避免报错 if ($preferences = $crawler->filterXPath('//button[@data-testid="accept-button"]')->first()) { $preferences->click(); // 等待页面元素加载完成 $this->client->waitFor('.lister-list'); } $element = $crawler->filterXPath('//h3[text()="1. Kenneth Branagh"]')->first(); $element->click(); $this->client->takeScreenshot('screenshot.jpg'); return 0; } }
关键说明
- Chrome无头模式:新版Chrome推荐使用
--headless=new参数,旧的--headless参数在Chrome 112+版本中行为变更,可能导致GUI无法隐藏。 - 参数传递方式:所有浏览器启动参数必须通过
ChromeOptions添加,再注入到DesiredCapabilities中,才能被Selenium Grid节点识别并应用到远程浏览器实例。 - 环境变量失效原因:
PANTHER_NO_HEADLESS是Panther针对本地Chrome客户端的环境变量,连接远程Grid时不会被解析,因此需要手动配置参数。
内容的提问来源于stack exchange,提问作者kkamara
相关产品推荐
相关产品推荐

