如何在java中使用selenium的firefox配置文件和firefox选项

np8igboo  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(380)

我正在编写一个我想无头的测试,它还将使用selenium在java中下载一个文件。从这里我了解到,您可以通过在初始化驱动程序之前抛出以下代码将驱动程序设置为无头:

options.setHeadless(true); //sets driver to work headless 
WebDriver driver = new FirefoxDriver(options);

我可以使用这个方法来编写一个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();

我要么不运行firefox的无头版本,要么在下载zip文件时得到一个弹出的保存提示。
如何组合这两个功能,配置文件和选项?
编辑:修复了 setHeadless(false) 成为 setHedless(true)

jmp7cifd

jmp7cifd1#

函数 options.setHeadless(false) 应该有一个 true 参数not false

guicsvcw

guicsvcw2#

通过使用新的firefox配置文件 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配置文件 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配置文件 FirefoxOptions 除了首选项之外,您还可以使用以下代码块:

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");

参考文献

您可以在中找到一些相关的详细讨论:
无法解析构造函数firefoxdriver(org.openqa.selenium.firefox.firefoxprofile)
无法在webdriver中传递firefoxprofile参数以使用首选项下载文件

相关问题