\n
\n","author":{"@type":"Person","name":"Divya"},"upvoteCount":0,"answerCount":1,"acceptedAnswer":null}}Reputation: 99
I am upgrading Selenium 3 to Selenium 4. One of the features in Selenium 4, is that DesriredCapabilities is deprecated. In some of the forms, it is mentioned that we can continue to use the deprecated class. Still, it is recommended we use browser-specific options e.g., ChromeOptions, FirefoxOptions, etc.
My question is, is there a way we can simplify the initialization of browser options and set the various capabilities for each of the browsers?
I see there is an abstract parent class AbstractDriverOtions used to declare the object and then instantiated separately as below. But is there a better way of implementing this?
Upvotes: 0
Views: 81
Reputation: 1996
public WebDriver initializeBrowser() {
String browser = System.getProperty("browser", "chrome").toLowerCase();
boolean isHeadless = Boolean.parseBoolean(System.getProperty("headless", "false"));
WebDriver driver;
switch (browser) {
case "firefox":
System.setProperty("webdriver.gecko.driver", "/path/to/geckodriver"); // Set path to Firefox driver
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.addArguments("--disable-notifications");
if (isHeadless) {
firefoxOptions.addArguments("--headless");
}
driver = new FirefoxDriver(firefoxOptions);
// Equivalent with WebDriverManager:
// WebDriver driver = WebDriverManager.getInstance("firefox").capabilities(firefoxOptions).create();
break;
case "safari":
SafariOptions safariOptions = new SafariOptions();
// Safari doesn't support headless mode, so we skip that option here
driver = new SafariDriver(safariOptions);
// Equivalent with WebDriverManager:
// WebDriver driver = WebDriverManager.getInstance("safari").capabilities(safariOptions).create();
break;
case "chrome":
default:
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver"); // Set path to Chrome driver
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--disable-notifications");
chromeOptions.addArguments("--start-maximized");
if (isHeadless) {
chromeOptions.addArguments("--headless");
}
driver = new ChromeDriver(chromeOptions);
// Equivalent with WebDriverManager:
// WebDriver driver = WebDriverManager.getInstance("chrome").capabilities(chromeOptions).create();
break;
}
return driver;
}
Upvotes: 0