我正在编写一个我想要 headless (headless)的测试,它还将使用 Selenium 在 java 中下载文件。来自here我了解到,您可以通过在初始化驱动程序之前抛出此代码来将驱动程序设置为 headless (headless):
options.setHeadless(true); //sets driver to work headless
WebDriver driver = new FirefoxDriver(options);
我可以使用这个method编写一个 Firefox 配置文件,它将指定一个下载目录,并允许我使用 Firefox 下载文件,而不会弹出任何窗口(我已经修改了该方法以允许该方法允许下载位置作为参数)。创建方法后,我在 main 中调用它,如下所示:
downloadPath = "C:\Scripts"
WebDriver driver = new FirefoxDriver(FirefoxDriverProfile(downloadPath));
然后说我想将以下代码与上述两种方法之一一起使用:
driver.get(https://github.com/mozilla/geckodriver/releases);
driver.findElement(By.linkText("geckodriver-v0.27.0-win64.zip")).click();
我要么不运行 headless (headless)版本的 Firefox,要么在下载 zip 文件时弹出保存提示。
如何组合这两个功能、配置文件和选项?
编辑:将 setHeadless(false)
修复为 setHedless(true)
最佳答案
使用新的Firefox Profile通过 FirefoxOptions
您可以使用以下代码块:
System.setProperty("webdriver.gecko.driver", "C:\\path\\to\\geckodriver.exe");
FirefoxOptions options = new FirefoxOptions();
options.setProfile(new FirefoxProfile());
WebDriver driver = new FirefoxDriver(options);
driver.get("https://www.google.com");
使用现有的 Firefox Profile通过 FirefoxOptions
您可以使用以下代码块:
System.setProperty("webdriver.gecko.driver", "C:\\path\\to\\geckodriver.exe");
ProfilesIni profile = new ProfilesIni();
FirefoxProfile testprofile = profile.getProfile("debanjan");
FirefoxOptions opt = new FirefoxOptions();
opt.setProfile(testprofile);
WebDriver driver = new FirefoxDriver(opt);
driver.get("https://www.google.com");
使用新的Firefox Profile通过 FirefoxOptions
以及 preferences您可以使用以下代码块:
String downloadFilepath = "C:\\path\\to\\MozillaFirefoxDownload";
System.setProperty("webdriver.gecko.driver", "C:\\path\\to\\geckodriver.exe");
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("browser.download.dir",downloadFilepath);
FirefoxOptions options = new FirefoxOptions();
options.setHeadless(true);
options.setProfile(profile);
WebDriver driver = new FirefoxDriver(options);
driver.get("https://www.google.com");
引用文献
您可以在以下位置找到一些相关的详细讨论:
关于java - 如何在 Java 中将 Firefox 配置文件和 Firefox 选项与 Selenium 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63477601/