java - 如何在 Java 中将 Firefox 配置文件和 Firefox 选项与 Selenium 一起使用

标签 java selenium firefox headless selenium-firefoxdriver

我正在编写一个我想要 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/

相关文章:

css - 在 Chrome、Safari 和 Edge 中显示 flex 对齐不正确,但在 Firefox 中正确

java - 分发库 Jar 时如何包含 scala 代码的 javadoc?

java - 部署 mybatis-truts 应用程序时出错

java - 基于 findElements 的列表循环是如何工作的?

javascript - jQuery 在 Firefox 和 IE 11 中运行不佳

javascript - setTimeout() 使用 iframe 移动 div 仅在 Firefox 中导致闪烁

java - 如何从java中的字节读取有符号整数?

java - 为什么 Groovy 编译器拒绝依赖 JSR308 类型注释编译器?

java - Selenium XPath - 如何查找紧邻前面的元素

javascript - Python 请求和 Forbes 'Welcome' 页面重定向