由于WebDriver在启动Firefox的时候,会启动一个全新的浏览器窗口,导致当前机器用户的浏览器配置信息在测试的时候都无法使用,例如一些已经安装的插件、个人收藏夹等。因此需要使用指定的配置文件来启动firefox浏览器窗口。
要启动带配置的Firefox窗口,首先要先生成一个自定义的Firefox浏览器配置文件:
(1)、打开cmd页面。
(2)、使用cd命令切换到firefox的所在目录,执行firefox.exe -ProfileManager -no-remote.
(3)、显示Firefox的“选择用户配置文件”对话框,如下图所示。
(4)、单击“创建配置文件”按钮,单击下一步,输入自动以配置文件的名称(webDriver),并单击完成按钮完成配置文件。
(5)、在“选择用户配置文件”对话框中,生成了名为“webDriver”的用户配置文件,选中“webDriver”选项后单击“启动Firefox”按钮。
具体实例代码如下:
扫描二维码关注公众号,回复:
169683 查看本文章
package cn.om.webdriverapi; import org.testng.annotations.Test; import org.testng.annotations.BeforeMethod; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxProfile; import org.openqa.selenium.firefox.internal.ProfilesIni; import org.testng.annotations.AfterMethod; public class TestFireFoxProfile { WebDriver driver; String URL; @Test public void testFireFoxProfile() { driver.get(URL); WebElement input = driver.findElement(By.id("kw")); input.sendKeys("webdriver"); driver.findElement(By.id("su")).click(); } @BeforeMethod public void beforeMethod() { URL = "http://www.baidu.com"; // 声明ProfilesIni对象 ProfilesIni allProfiles = new ProfilesIni(); // 调用allProfiles对象的getProfile方法获取名为“WebDriver”的用户配置文件 FirefoxProfile profile = allProfiles.getProfile("WebDriver"); // 调用profile对象的setPreference方法,设定浏览器启动时首页显示为sogou profile.setPreference("browser.startup.homepage", "http://www.sogou.com"); // 指定Profile对象作为参数,实例化FirefoxDriver对象 // 实现使用指定Profile配置文件启动Firefox浏览器窗口 System.setProperty("webdriver.firefox.bin", "D:/Mozilla Firefox/firefox.exe"); driver = new FirefoxDriver(profile); } @AfterMethod public void afterMethod() { driver.quit(); } }