下面列出了怎么用org.openqa.selenium.firefox.FirefoxBinary的API类实例代码及写法,或者点击链接到github查看源代码。
@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;
}
/**
*
* @param config
* @return A FirefoxDriver.
*/
@Override
public RemoteWebDriver make(HashMap<String, String> config) {
FirefoxBinary ffBinary = new FirefoxBinary();
if (System.getProperty(DISPLAY_PROPERTY) != null) {
ffBinary.setEnvironmentProperty(
DISPLAY_PROPERTY.toUpperCase(),
System.getProperty(DISPLAY_PROPERTY));
} else if (System.getenv(DISPLAY_PROPERTY.toUpperCase()) != null) {
ffBinary.setEnvironmentProperty(
DISPLAY_PROPERTY.toUpperCase(),
System.getenv(DISPLAY_PROPERTY.toUpperCase()));
}
RemoteWebDriver remoteWebDriver = new FirefoxDriver(ffBinary, firefoxProfile);
if (screenHeight != -1 && screenWidth!= -1) {
remoteWebDriver.manage().window().setSize(new Dimension(screenWidth, screenHeight));
}
return remoteWebDriver;
}
@Override
protected XpiDriverService createDriverService(
File exe,
int port,
Duration timeout,
List<String> args,
Map<String, String> environment) {
try {
return new XpiDriverService(
exe,
port,
timeout,
args,
environment,
binary == null ? new FirefoxBinary() : binary,
profile == null ? new FirefoxProfile() : profile,
getLogFile());
} catch (IOException e) {
throw new WebDriverException(e);
}
}
@Test
public void builderPassesTimeoutToDriverService() {
File exe = new File("someFile");
Duration defaultTimeout = Duration.ofSeconds(45);
Duration customTimeout = Duration.ofSeconds(60);
FirefoxProfile mockProfile = mock(FirefoxProfile.class);
FirefoxBinary mockBinary = mock(FirefoxBinary.class);
XpiDriverService.Builder builderMock = spy(XpiDriverService.Builder.class);
builderMock.withProfile(mockProfile);
builderMock.withBinary(mockBinary);
doReturn(exe).when(builderMock).findDefaultExecutable();
builderMock.build();
verify(builderMock).createDriverService(any(), anyInt(), eq(defaultTimeout), any(), any());
builderMock.withTimeout(customTimeout);
builderMock.build();
verify(builderMock).createDriverService(any(), anyInt(), eq(customTimeout), any(), any());
}
@Override
public void start() throws CandybeanException {
String profileName = candybean.config.getValue("browser.firefox.profile", "default");
File ffBinaryPath = new File(candybean.config.getPathValue("browser.firefox.binary"));
if(!ffBinaryPath.exists()){
String error = "Unable to find firefox browser driver from the specified location in the configuration file! \n"
+ "Please add a configuration to the candybean config file for key \"browser.firefox.binary\" that"
+ "indicates the location of the binary.";
logger.severe(error);
throw new CandybeanException(error);
} else {
FirefoxProfile ffProfile = (new ProfilesIni()).getProfile(profileName);
FirefoxBinary ffBinary = new FirefoxBinary(ffBinaryPath);
logger.info("Instantiating Firefox with profile name: "
+ profileName + " and binary path: " + ffBinaryPath);
super.wd = new FirefoxDriver(ffBinary, ffProfile);
super.start(); // requires wd to be instantiated first
}
}
/**
*
* @param filePath
* the binary path location of the firefox app (where it's
* installed)
* @return
*/
private static FirefoxBinary getFFBinary(String filePath) {
File[] possibleLocations = { new File(filePath != null ? filePath : ""),
new File("C:\\Program Files\\Mozilla Firefox\\firefox.exe"),
new File("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe"), };
File ffbinary = null;
for (File curr : possibleLocations) {
if (curr.exists()) {
ffbinary = curr;
break;
}
}
if (ffbinary == null) {
throw new RuntimeException(
"Unable to find firefox binary, please ensure that firefox is installed "
+ "on your system. If it is then please determine the path to your firefox.exe and set it as "
+ "binaryPath=<FIREFOX PATH HERE>");
} else {
return new FirefoxBinary(ffbinary);
}
}
@Override
public WebDriver createWebDriver(String webDriverPath) {
FirefoxBinary ffox = new FirefoxBinary();
if ("true".equals(System.getenv("TRAVIS"))) {
// xvfb is supposed to run with DISPLAY 99
ffox.setEnvironmentProperty("DISPLAY", ":99");
}
ffox.addCommandLineOptions("--headless");
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.download.dir",
FileUtils.getTempDirectory().toString() + "/firefox/");
profile.setPreference("browser.helperApps.alwaysAsk.force", false);
profile.setPreference("browser.download.manager.showWhenStarting", false);
profile.setPreference("browser.download.manager.showAlertOnComplete", false);
profile.setPreference("browser.download.manager.closeWhenDone", true);
profile.setPreference("app.update.auto", false);
profile.setPreference("app.update.enabled", false);
profile.setPreference("dom.max_script_run_time", 0);
profile.setPreference("dom.max_chrome_script_run_time", 0);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk",
"application/x-ustar,application/octet-stream,application/zip,text/csv,text/plain");
profile.setPreference("network.proxy.type", 0);
System.setProperty(
GeckoDriverService.GECKO_DRIVER_EXE_PROPERTY, webDriverPath);
System.setProperty(
FirefoxDriver.SystemProperty.DRIVER_USE_MARIONETTE, "true");
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setBinary(ffox);
firefoxOptions.setProfile(profile);
firefoxOptions.setLogLevel(FirefoxDriverLogLevel.TRACE);
return new FirefoxDriver(firefoxOptions);
}
/**
* 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");
}
public SeleniumConfig(long timeout) {
FirefoxBinary firefoxBinary = new FirefoxBinary();
firefoxBinary.addCommandLineOptions("--headless");
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setBinary(firefoxBinary);
driver = new FirefoxDriver(firefoxOptions);
driver.manage().timeouts().implicitlyWait(timeout, TimeUnit.SECONDS);
}
@Override
protected FirefoxDriver createBrowser() {
FirefoxOptions desiredCapabilities = new FirefoxOptions(createCapabilities());
desiredCapabilities.setCapability(FirefoxDriver.PROFILE, createProfile());
return new FirefoxDriver(new GeckoDriverService.Builder().usingFirefoxBinary(new FirefoxBinary()).build(),
desiredCapabilities);
}
/**
* 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);
}
/**
* Creates a {@link FirefoxBinary} object and sets the path, but only if the path is not blank.
*
* @param pathToBrowser
* the path to the browser binary
* @return the Firefox binary
*/
private static FirefoxBinary createFirefoxBinary(final String pathToBrowser)
{
if (StringUtils.isNotBlank(pathToBrowser))
{
return new FirefoxBinary(new File(pathToBrowser));
}
else
{
return new FirefoxBinary();
}
}
@Override
protected WebDriver initialValue()
{
System.setProperty("webdriver.gecko.driver", ApplicationConfigProvider.getInstance().getDriverLocation());
FirefoxBinary firefoxBinary = new FirefoxBinary();
firefoxBinary.addCommandLineOptions("--headless");
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setBinary(firefoxBinary);
return new FirefoxDriver(firefoxOptions); // can be replaced with other browser drivers
}
/**
* @return The binary used to run firefox if it was set via the FIREFOX_BINARY system property,
* or null if the FIREFOX_BINARY system property was not defined
*/
private FirefoxBinary getFirefoxBinary() {
final String firefoxBinary = SYSTEM_PROPERTY_UTILS.getProperty(Constants.FIREFOX_BINARY);
if (firefoxBinary != null) {
return new FirefoxBinary(new File(firefoxBinary));
}
return new FirefoxBinary();
}
private FirefoxDriver createFirefoxDriver(String display, String binaryPath,
DesiredCapabilities desiredCapabilities)
{
FirefoxProfile profile = createDefaultFirefoxProfile();
FirefoxBinary binary = !StringUtils.isBlank(binaryPath) ? new FirefoxBinary(new File(binaryPath))
: new FirefoxBinary();
LOG.info("Binding to {} display", display);
availableDisplays.compute(display, (d, value) -> value == null ? 1 : value + 1);
binary.setEnvironmentProperty(DISPLAY, display);
LOG.info("Firefox path is: {}", binaryPath);
return openFirefoxDriver(desiredCapabilities, profile, binary);
}
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);
}
}
@Override
public boolean isAvailable() {
try {
// This will search $PATH looking for the binary. It's not perfect, since the user may be
// setting the path to the binary with a capability, but this will work in almost all common
// cases.
new FirefoxBinary();
return true;
} catch (IllegalStateException | WebDriverException e) {
return false;
}
}
private XpiDriverService(
File executable,
int port,
Duration timeout,
List<String> args,
Map<String, String> environment,
FirefoxBinary binary,
FirefoxProfile profile,
File logFile)
throws IOException {
super(executable, port, timeout, args, environment);
this.port = Require.positive("Port", port);
this.binary = binary;
this.profile = profile;
String firefoxLogFile = System.getProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE);
if (firefoxLogFile != null) { // System property has higher precedence
if ("/dev/stdout".equals(firefoxLogFile)) {
sendOutputTo(System.out);
} else if ("/dev/stderr".equals(firefoxLogFile)) {
sendOutputTo(System.err);
} else if ("/dev/null".equals(firefoxLogFile)) {
sendOutputTo(ByteStreams.nullOutputStream());
} else {
sendOutputTo(new FileOutputStream(firefoxLogFile));
}
} else {
if (logFile != null) {
// TODO: This stream is leaked.
sendOutputTo(new FileOutputStream(logFile));
} else {
sendOutputTo(ByteStreams.nullOutputStream());
}
}
}
@Override
protected File findDefaultExecutable() {
if (binary == null) {
return new FirefoxBinary().getFile();
}
return binary.getFile();
}
public FirefoxBrowserFactory usingBinary(FirefoxBinary fb) {
binary = fb;
return this;
}
public Builder withBinary(FirefoxBinary binary) {
this.binary = Require.nonNull("Firefox binary", binary);
return this;
}