下面列出了怎么用org.openqa.selenium.firefox.FirefoxDriver的API类实例代码及写法,或者点击链接到github查看源代码。
public Shadow(WebDriver driver) {
if (driver instanceof ChromeDriver) {
sessionId = ((ChromeDriver)driver).getSessionId();
chromeDriver = (ChromeDriver)driver;
} else if (driver instanceof FirefoxDriver) {
sessionId = ((FirefoxDriver)driver).getSessionId();
firfoxDriver = (FirefoxDriver)driver;
} else if (driver instanceof InternetExplorerDriver) {
sessionId = ((InternetExplorerDriver)driver).getSessionId();
ieDriver = (InternetExplorerDriver)driver;
} else if (driver instanceof RemoteWebDriver) {
sessionId = ((RemoteWebDriver)driver).getSessionId();
remoteWebDriver = (RemoteWebDriver)driver;
}
this.driver = driver;
}
@BeforeAll
public static void openServerAndBrowser() throws IOException {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
// ChromeOptions options = new ChromeOptions();
// options.addArguments(
// "--headless",
// "--disable-web-security",
// "--allow-running-insecure-content",
// "--ignore-certificate-errors");
driver = new FirefoxDriver(options);
percy = new Percy(driver);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
public static void main(String... args) throws IOException {
System.setProperty("webdriver.gecko.driver",
"./src/test/resources/drivers/geckodriver 2");
FirefoxProfile profile = new FirefoxProfile();
profile.addExtension(
new File("./src/test/resources/extensions/xpath_finder.xpi"));
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setProfile(profile);
FirefoxDriver driver = new FirefoxDriver(firefoxOptions);
try {
driver.get("http://www.google.com");
} finally {
driver.quit();
}
}
public static void main(String... args) {
System.setProperty("webdriver.gecko.driver",
"./src/test/resources/drivers/geckodriver 2");
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("browser.shell.checkDefaultBrowser", true);
profile.setAssumeUntrustedCertificateIssuer(false);
profile.setAcceptUntrustedCertificates(false);
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setProfile(profile);
FirefoxDriver driver = new FirefoxDriver(firefoxOptions);
driver.get("http://facebook.com");
}
/**
* Properly Returns the WebDriver Object to the pool when finished or
* close and quit the driver if the object pool is not used
*/
private void properlyCloseWebDriver() {
getLog().debug("Closing Firefox driver.");
if (firefoxDriverObjectPool != null &&
getDriver() instanceof FirefoxDriver) {
//set the blank page before returning the webDriver instance
getDriver().get("");
try {
firefoxDriverObjectPool.returnObject((FirefoxDriver)getDriver());
} catch (Exception ex) {
getLog().warn("Firefox driver cannot be returned due to " + ex.getMessage());
}
} else {
try {
getDriver().close();
getDriver().quit();
} catch (Exception e) {
getLog().warn("An error occured while closing driver."
+ " A defunct firefox process may run on the system. "
+ " Trying to kill before leaving");
if (getDriver() instanceof FirefoxDriver) {
((FirefoxDriver)getDriver()).kill();
}
}
}
}
private static FirefoxDriver createFirefoxDriver() {
FirefoxOptions options = new FirefoxOptions();
if (BrowserConfig.getFirefoxBinPath() != null) {
options.setBinary(BrowserConfig.getFirefoxBinPath());
}
if (BrowserConfig.getFirefoxDriverPath() != null) {
System.setProperty(FIREFOX_DRIVER_PATH_KEY, BrowserConfig.getChromeDriverPath().toString());
}
if (BrowserConfig.isHeadless()) {
options.setHeadless(true);
}
if (System.getProperty(FIREFOX_DRIVER_PATH_KEY) == null) {
setupDriverManagerConfig();
downloadDriverMessage("firefox");
WebDriverManager.firefoxdriver().setup();
}
return new FirefoxDriver(options);
}
public static DesiredCapabilities build(RemoteCapability capability){
DesiredCapabilities desiredCapabilities;
if(RemoteCapability.CHROME.equals(capability)){
ChromeOptions options = new ChromeOptions();
desiredCapabilities = DesiredCapabilities.chrome();
desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, options);
return desiredCapabilities;
} else if (RemoteCapability.FIREFOX.equals(capability)){
FirefoxProfile profile = new FirefoxProfile();
desiredCapabilities = DesiredCapabilities.firefox();
desiredCapabilities.setCapability(FirefoxDriver.PROFILE, profile);
return desiredCapabilities;
} else if (RemoteCapability.INTERNET_EXPLORER.equals(capability)){
desiredCapabilities = DesiredCapabilities.internetExplorer();
return desiredCapabilities;
} else if (RemoteCapability.PHANTOMJS.equals(capability)){
desiredCapabilities = DesiredCapabilities.phantomjs();
return desiredCapabilities;
}
throw new IllegalArgumentException("No such capability");
}
public static WebDriver getFirefoxDriver(){
/*
Need to have an updated Firefox, but also need
to download and put the geckodriver in your own home dir.
See:
https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver
https://github.com/mozilla/geckodriver/releases
However, drivers for FireFox have been often unstable.
Therefore, I do recommend to use Chrome instead
*/
setupDriverExecutable("geckodriver", "webdriver.gecko.driver");
DesiredCapabilities desiredCapabilities = DesiredCapabilities.firefox();
desiredCapabilities.setCapability("marionette", true);
desiredCapabilities.setJavascriptEnabled(true);
return new FirefoxDriver(desiredCapabilities);
}
@Override
public void resolve() {
try {
Optional<Object> testInstance = context.getTestInstance();
Optional<Capabilities> capabilities = annotationsReader
.getCapabilities(parameter, testInstance);
FirefoxOptions firefoxOptions = (FirefoxOptions) getOptions(
parameter, testInstance);
if (capabilities.isPresent()) {
firefoxOptions.merge(capabilities.get());
}
object = new FirefoxDriver(firefoxOptions);
} catch (Exception e) {
handleException(e);
}
}
@Override
public FirefoxDriver makeObject() throws Exception {
FirefoxBinary ffBinary = new FirefoxBinary();
if (System.getProperty(DISPLAY_PROPERTY_KEY) != null) {
Logger.getLogger(this.getClass()).info("Setting Xvfb display with value " + System.getProperty(DISPLAY_PROPERTY_KEY));
ffBinary.setEnvironmentProperty("DISPLAY", System.getProperty(DISPLAY_PROPERTY_KEY));
}
FirefoxDriver fd = new FirefoxDriver(ffBinary, ProfileFactory.getInstance().getScenarioProfile());
if (this.implicitelyWaitDriverTimeout != null) {
fd.manage().timeouts().implicitlyWait(this.implicitelyWaitDriverTimeout.longValue(), TimeUnit.SECONDS);
}
if (this.pageLoadDriverTimeout != null) {
fd.manage().timeouts().pageLoadTimeout(this.pageLoadDriverTimeout.longValue(), TimeUnit.SECONDS);
}
return fd;
}
public static WebDriver getFirefoxDriver(){
/*
Need to have an updated Firefox, but also need
to download and put the geckodriver in your own home dir.
See:
https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver
https://github.com/mozilla/geckodriver/releases
However, drivers for FireFox have been often unstable.
Therefore, I do recommend to use Chrome instead
*/
setupDriverExecutable("geckodriver", "webdriver.gecko.driver");
DesiredCapabilities desiredCapabilities = DesiredCapabilities.firefox();
desiredCapabilities.setCapability("marionette", true);
desiredCapabilities.setJavascriptEnabled(true);
return new FirefoxDriver(desiredCapabilities);
}
static Stream<Arguments> forcedTestProvider() {
return Stream.of(
Arguments.of(AppiumDriverHandler.class,
ForcedAppiumJupiterTest.class, AppiumDriver.class,
"appiumNoCapabilitiesTest"),
Arguments.of(AppiumDriverHandler.class,
ForcedAppiumJupiterTest.class, AppiumDriver.class,
"appiumWithCapabilitiesTest"),
Arguments.of(ChromeDriverHandler.class,
ForcedBadChromeJupiterTest.class, ChromeDriver.class,
"chromeTest"),
Arguments.of(FirefoxDriverHandler.class,
ForcedBadFirefoxJupiterTest.class, FirefoxDriver.class,
"firefoxTest"),
Arguments.of(EdgeDriverHandler.class,
ForcedEdgeJupiterTest.class, EdgeDriver.class,
"edgeTest"),
Arguments.of(OperaDriverHandler.class,
ForcedOperaJupiterTest.class, OperaDriver.class,
"operaTest"),
Arguments.of(SafariDriverHandler.class,
ForcedSafariJupiterTest.class, SafariDriver.class,
"safariTest"));
}
@BeforeMethod
public void setUpProxy() throws Exception {
DesiredCapabilities capabilities = new DesiredCapabilities();
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("network.proxy.type", 1);
profile.setPreference("network.proxy.http", proxyIp);
profile.setPreference("network.proxy.http_port", port);
capabilities.setCapability(FirefoxDriver.PROFILE, profile);
driver = new FirefoxDriver(capabilities);
//or
//driver = new FirefoxDriver(profile);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
/**
* 如果当前进程没有绑定driver,创建一个然后绑定上,如果已经有了就直接返回
* create a driver for this thread if not exist. or return it directly
*/
public static WebDriver getDriver(){
WebDriver driver= DriverManager.ThreadDriver.get();
if (driver==null){
if (browserType.equals("firefox")){
driver = new EventFiringWebDriver(new FirefoxDriver()).register(new LogEventListener());
ThreadDriver.set(driver);
//找东西前等三秒wait 3 second for every find by
DriverManager.getDriver().manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
}
//有需求的同学自己在这里添加IE等浏览器的支持
//you can add ie/chrome or other driver here
}
return driver;
}
@Test
public void bounceThatWindow(){
WebDriver driver = new FirefoxDriver();
driver.get("file://" + System.getProperty("user.dir") + "/jsrunner.html");
driver.manage().window().maximize();
Dimension fullScreenSize = driver.manage().window().getSize();
int changeWidth = 200; int changeHeight = 210;
int xDir = 8; int yDir = 8; int xDirIncrement = xDir; int yDirIncrement = yDir;
driver.manage().window().setSize(new Dimension(changeWidth,changeHeight));
Point position = driver.manage().window().getPosition();
String banner = "***BANG****........ AND THEY ARE OFF........ Automation can be fun. " +
" EvilTester.com present a javascript and browser" +
" animation using Selenium 2 WebDriver tribute to the" +
" sporting event that cannot be named lest we be sued";
int bannerStart = 0;
for(int bounceIterations = 0; bounceIterations < 1000; bounceIterations ++){
position = position.moveBy(xDir,yDir);
driver.manage().window().setPosition(position);
if(position.getX()>(fullScreenSize.getWidth() - changeWidth)){ xDir = -1 * xDirIncrement; }
if(position.getX()<0){ xDir = xDirIncrement; }
if(position.getY()>(fullScreenSize.getHeight() - changeHeight)){ yDir = -1 * yDirIncrement; }
if(position.getY()<0){ yDir = yDirIncrement; }
//try {Thread.sleep(20);} catch (InterruptedException e) {}
String displayBanner = banner.substring(bannerStart,bannerStart+30);
((JavascriptExecutor)driver).executeScript("document.title='" + displayBanner + "';");
bannerStart++;
if(bannerStart > banner.length()-35){banner += banner;}
}
driver.quit();
}
private IBrowserFactory getCustomFactory() {
return () -> {
FirefoxSettings firefoxSettings = new FirefoxSettings(AqualityServices.get(ISettingsFile.class));
WebDriverManager.firefoxdriver().setup();
FirefoxDriver driver = new FirefoxDriver(firefoxSettings.getCapabilities().setHeadless(true));
return new Browser(driver);
};
}
/**
* Sets the webdriver to FireFox. We set our optimal parameters here
* to ensure our proxy is set correctly.
*/
private void setFirefoxDriver() {
FirefoxOptions options = new FirefoxOptions();
FirefoxProfile profile = new FirefoxProfile();
FirefoxBinary binary = new FirefoxBinary(this.driverLocation);
LoggingPreferences logPrefs = new LoggingPreferences();
System.setProperty(FirefoxDriver.SystemProperty.DRIVER_USE_MARIONETTE,"true");
// hide firefox logs from console
System.setProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE,"/tmp/rust_");
profile.setPreference("media.volume_scale", "0.0");
profile.setPreference("general.useragent.override", userAgent.randomUA());
profile.setPreference("network.proxy.type", 1);
profile.setPreference("network.proxy.http", this.proxies.getCurrentProxyModel().getIp());
profile.setPreference("network.proxy.http_port", this.proxies.getCurrentProxyModel().getPort());
profile.setPreference("network.proxy.ssl", this.proxies.getCurrentProxyModel().getIp());
profile.setPreference("network.proxy.ssl_port", this.proxies.getCurrentProxyModel().getPort());
logPrefs.enable(LogType.BROWSER, Level.ALL);
logPrefs.enable(LogType.PERFORMANCE, Level.INFO);
options.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
options.setProfile(profile);
options.setHeadless(true);
options.setBinary(binary);
// options.setProxy(this.proxies.getCurrentProxy());
options.setCapability("proxy", this.proxies.getCurrentProxy());
this.webDriver = new FirefoxDriver(options);
Log.WINFO(this.workerName, this.workerColor, "Firefox Driver Set");
}
private static WebDriver setupFirefoxDriver() throws MalformedURLException {
LOG.i("Setting up Firefox driver...");
setupDriver(firefoxdriver());
final DesiredCapabilities capabilities = new DesiredCapabilities();
final FirefoxOptions options = new FirefoxOptions(capabilities);
final GeckoDriverService firefoxService = GeckoDriverService.createDefaultService();
return new FirefoxDriver(firefoxService, options);
}
@Test
public void bounceThatWindow(){
WebDriver driver = new FirefoxDriver();
driver.get("file://" + System.getProperty("user.dir") + "/jsrunner.html");
driver.manage().window().maximize();
Dimension fullScreenSize = driver.manage().window().getSize();
int changeWidth = 200; int changeHeight = 210;
int xDir = 8; int yDir = 8; int xDirIncrement = xDir; int yDirIncrement = yDir;
driver.manage().window().setSize(new Dimension(changeWidth,changeHeight));
Point position = driver.manage().window().getPosition();
String banner = "***BANG****........ AND THEY ARE OFF........ Automation can be fun. " +
" EvilTester.com present a javascript and browser" +
" animation using Selenium 2 WebDriver tribute to the" +
" sporting event that cannot be named lest we be sued";
int bannerStart = 0;
for(int bounceIterations = 0; bounceIterations < 1000; bounceIterations ++){
position = position.moveBy(xDir,yDir);
driver.manage().window().setPosition(position);
if(position.getX()>(fullScreenSize.getWidth() - changeWidth)){ xDir = -1 * xDirIncrement; }
if(position.getX()<0){ xDir = xDirIncrement; }
if(position.getY()>(fullScreenSize.getHeight() - changeHeight)){ yDir = -1 * yDirIncrement; }
if(position.getY()<0){ yDir = yDirIncrement; }
//try {Thread.sleep(20);} catch (InterruptedException e) {}
String displayBanner = banner.substring(bannerStart,bannerStart+30);
((JavascriptExecutor)driver).executeScript("document.title='" + displayBanner + "';");
bannerStart++;
if(bannerStart > banner.length()-35){banner += banner;}
}
driver.quit();
}
@Test
public void shouldCreateFirefox() throws Exception {
FirefoxDriver mockFirefoxDriver = Mockito.mock(FirefoxDriver.class);
whenNew(FirefoxDriver.class)
.withParameterTypes(GeckoDriverService.class, FirefoxOptions.class)
.withArguments(isA(GeckoDriverService.class), isA(FirefoxOptions.class))
.thenReturn(mockFirefoxDriver);
final FirefoxDriver browser = config.createBrowser();
assertThat(browser, is(mockFirefoxDriver));
verifyNew(FirefoxDriver.class, times(1)).withArguments(isA(GeckoDriverService.class), isA(FirefoxOptions.class));
}
public boolean connectToFirefoxDriverAtWithProfile(String url, Map<String, Object> profile)
throws MalformedURLException {
FirefoxProfile fxProfile = getFirefoxProfile(profile);
DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
desiredCapabilities.setCapability("browserName", "firefox");
desiredCapabilities.setCapability(FirefoxDriver.PROFILE, fxProfile);
return createAndSetRemoteDriver(url, desiredCapabilities);
}
private FirefoxOptions getGeckoOptions() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, this.alertBehaviour);
options.setCapability(FirefoxDriver.MARIONETTE, true);
options.setCapability("platform", platform);
options.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
setLoggingPrefs(options);
return options;
}
public VaadinLocaleTest(String language, String expectedLanuage) {
this.expectedLanguage = expectedLanuage;
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("intl.accept_languages", language);
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setProfile(profile);
WebDriver webDriver = new FirefoxDriver(firefoxOptions);
startBrowser(webDriver);
}
@Override
public FirefoxDriver getObject() throws BeansException {
if (properties.getFirefox().isEnabled()) {
try {
return new FirefoxDriver();
} catch (WebDriverException e) {
e.printStackTrace();
// swallow the exception
}
}
return null;
}
@Bean
FirefoxDriverFactory firefoxDriverFactory() {
FirefoxDriverFactory factory =
mock(FirefoxDriverFactory.class);
given(factory.getObject())
.willReturn(mock(FirefoxDriver.class));
return factory;
}
/**
* Generates a firefox webdriver.
*
* @return
* A firefox webdriver
* @throws TechnicalException
* if an error occured when Webdriver setExecutable to true.
*/
private WebDriver generateFirefoxDriver() throws TechnicalException {
final String pathWebdriver = DriverFactory.getPath(Driver.FIREFOX);
if (!new File(pathWebdriver).setExecutable(true)) {
throw new TechnicalException(Messages.getMessage(TechnicalException.TECHNICAL_ERROR_MESSAGE_WEBDRIVER_SET_EXECUTABLE));
}
log.info("Generating Firefox driver ({}) ...", pathWebdriver);
System.setProperty(Driver.FIREFOX.getDriverName(), pathWebdriver);
final FirefoxOptions firefoxOptions = new FirefoxOptions();
final FirefoxBinary firefoxBinary = new FirefoxBinary();
firefoxOptions.setCapability(CapabilityType.ForSeleniumServer.ENSURING_CLEAN_SESSION, true);
firefoxOptions.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.ACCEPT);
setLoggingLevel(firefoxOptions);
// Proxy configuration
if (Context.getProxy().getProxyType() != ProxyType.UNSPECIFIED && Context.getProxy().getProxyType() != ProxyType.AUTODETECT) {
firefoxOptions.setCapability(CapabilityType.PROXY, Context.getProxy());
}
if (Context.isHeadless()) {
firefoxBinary.addCommandLineOptions("--headless");
firefoxOptions.setBinary(firefoxBinary);
}
firefoxOptions.setLogLevel(FirefoxDriverLogLevel.FATAL);
return new FirefoxDriver(firefoxOptions);
}
/**
* Most basic Selenium example that searches for a term on google.
* Does not close the browser on test completion to keep the test as simple as possible.
*/
@Test
public void simpleTest() {
WebDriver driver = new FirefoxDriver();
driver.get("http://google.com/?hl=en");
WebElement searchBox = driver.findElement(name("q"));
searchBox.sendKeys("adf selenium");
searchBox.submit();
}
@Test
public void checkEnv(){
//首先打一个hello world来测试一你的IDE里testng的插件是否已经安装好
//check if you success installed testng on your IDE
System.out.println("Hello World, TestNG");
//看看你电脑上能不能正确用firefox driver启动firefox
//check if firefox driver runs successfully on your computer
WebDriver driver=new FirefoxDriver();
driver.get("https://github.com/zhangting85/simpleWebtest");
}
public BrowserStatement()
{
// that is like a dirty hack to provide testing ability
if (multibrowserConfiguration == null)
multibrowserConfiguration = MultibrowserConfiguration.getInstance();
final String ieDriverPath = Neodymium.configuration().getIeDriverPath();
final String chromeDriverPath = Neodymium.configuration().getChromeDriverPath();
final String geckoDriverPath = Neodymium.configuration().getFirefoxDriverPath();
// shall we run old school firefox?
final boolean firefoxLegacy = Neodymium.configuration().useFirefoxLegacy();
System.setProperty(FirefoxDriver.SystemProperty.DRIVER_USE_MARIONETTE, Boolean.toString(!firefoxLegacy));
if (!StringUtils.isEmpty(ieDriverPath))
{
System.setProperty("webdriver.ie.driver", ieDriverPath);
}
if (!StringUtils.isEmpty(chromeDriverPath))
{
System.setProperty("webdriver.chrome.driver", chromeDriverPath);
}
if (!StringUtils.isEmpty(geckoDriverPath))
{
System.setProperty("webdriver.gecko.driver", geckoDriverPath);
}
// get test specific browser definitions (aka browser tag see browser.properties)
// could be one value or comma separated list of values
String browserDefinitionsProperty = System.getProperty(SYSTEM_PROPERTY_BROWSERDEFINITION, "");
browserDefinitionsProperty = browserDefinitionsProperty.replaceAll("\\s", "");
// parse test specific browser definitions
if (!StringUtils.isEmpty(browserDefinitionsProperty))
{
browserDefinitions.addAll(Arrays.asList(browserDefinitionsProperty.split(",")));
}
}
private FirefoxDriver openFirefoxDriver(DesiredCapabilities desiredCapabilities, FirefoxProfile profile,
FirefoxBinary binary)
{
try
{
return new FirefoxDriver(binary, profile, desiredCapabilities);
}
catch (WebDriverException ex)
{
LOG.warn(ex.getMessage());
awakenAllDrivers();
return openFirefoxDriver(desiredCapabilities, profile, binary);
}
}