如何使用 Selenium + Java 在 Google Chrome 弹出窗口中自动单击 "Allow"

How to click "Allow" automatically on Google Chrome pop-up using Selenium + Java

根据我所读的内容,有一种方法可以为 Google Chrome 版本 < 50 执行此操作,还有一种方法可以为 Google Chrome 执行此操作版本 > 50。我正在使用 Google Chrome 91.

这里有一个答案: 其中指出我需要做这样的事情:

//Create a map to store  preferences 
Map<String, Object> prefs = new HashMap<String, Object>();

//add key and value to map as follow to switch off browser notification
//Pass the argument 1 to allow and 2 to block
prefs.put("profile.default_content_setting_values.notifications", 2);

//Create an instance of ChromeOptions 
ChromeOptions options = new ChromeOptions();

// set ExperimentalOption - prefs 
options.setExperimentalOption("prefs", prefs);

//Now Pass ChromeOptions instance to ChromeDriver Constructor to initialize chrome driver which will switch off this browser notification on the chrome browser
WebDriver driver = new ChromeDriver(options);

但是,这对我不起作用。这就是弹出窗口的样子

这就是我的使用方式:

// Create a map to store preferences (to disable pop-up notifications)
Map<String, Object> prefs = new HashMap<String, Object>();

// add key and value to map as follow to switch off browser notification
// Pass the argument 1 to allow and 2 to block
prefs.put("profile.default_content_setting_values.notifications", 2);

// for local automated testing
this.chromeOptions = new ChromeOptions();
chromeOptions.setExperimentalOption("prefs", prefs);
chromeOptions.addArguments("--disable-notifications");
chromeOptions.addArguments("start-maximized");
String chromeDriverPath = "resources/chromedriver-91.exe";
System.setProperty("webdriver.chrome.driver", chromeDriverPath);
this.driver = new ChromeDriver(chromeOptions);
System.out.println("new chrome driver started.....");
this.driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

如您所见,我尝试了多种不同的方法。 "--disable-notifications" 无效,chromeOptions.setExperimentalOption("prefs", prefs); 也无效 当我 运行 我的程序时,弹出窗口仍然存在,我需要 Selenium 在弹出窗口上单击“允许”,这样我才能继续程序的其余部分。

您正在尝试下载文件,这是与显示通知不同的行为。尝试

prefs.put("profile.default_content_setting_values.automatic_downloads", 1);