Best Selenium code snippet using org.openqa.selenium.remote.Interface BrowserType
Source:WebDriverFactory.java
1/*2 * Copyright (C) 2015 The Minium Authors3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16package minium.web.config;17import static java.lang.String.format;18import java.io.File;19import java.io.IOException;20import java.util.List;21import java.util.Set;22import org.openqa.selenium.Capabilities;23import org.openqa.selenium.Dimension;24import org.openqa.selenium.MutableCapabilities;25import org.openqa.selenium.Point;26import org.openqa.selenium.TakesScreenshot;27import org.openqa.selenium.WebDriver;28import org.openqa.selenium.chrome.ChromeDriver;29import org.openqa.selenium.chrome.ChromeOptions;30import org.openqa.selenium.firefox.FirefoxDriver;31import org.openqa.selenium.firefox.FirefoxOptions;32import org.openqa.selenium.firefox.FirefoxProfile;33import org.openqa.selenium.ie.InternetExplorerDriver;34import org.openqa.selenium.ie.InternetExplorerOptions;35import org.openqa.selenium.remote.Augmenter;36import org.openqa.selenium.remote.BrowserType;37import org.openqa.selenium.remote.DesiredCapabilities;38import org.openqa.selenium.remote.LocalFileDetector;39import org.openqa.selenium.remote.RemoteWebDriver;40import org.openqa.selenium.remote.service.DriverService;41import org.openqa.selenium.safari.SafariDriver;42import org.openqa.selenium.safari.SafariOptions;43import com.google.common.base.Strings;44import com.google.common.collect.Sets;45import minium.web.StatefulWebDriver;46import minium.web.config.WebDriverProperties.ChromeOptionsProperties;47import minium.web.config.WebDriverProperties.DimensionProperties;48import minium.web.config.WebDriverProperties.FirefoxProfileProperties;49import minium.web.config.WebDriverProperties.PointProperties;50import minium.web.config.WebDriverProperties.PreferenceProperties;51import minium.web.config.WebDriverProperties.WindowProperties;52import minium.web.config.services.ChromeDriverServiceProperties;53import minium.web.config.services.DriverServicesProperties;54import minium.web.config.services.FirefoxDriverServiceProperties;55import minium.web.config.services.InternetExplorerDriverServiceProperties;56public class WebDriverFactory {57 public interface WebDriverTransformer {58 public WebDriver transform(WebDriver wd);59 }60 private final DriverServicesProperties driverServices;61 enum WebDriverType {62 CHROME(BrowserType.CHROME, BrowserType.GOOGLECHROME) {63 @SuppressWarnings("deprecation")64 @Override65 public WebDriver create(WebDriverFactory webDriverFactory, DesiredCapabilities desiredCapabilities) {66 ChromeDriverServiceProperties serviceProperties = webDriverFactory.driverServices == null ? null : webDriverFactory.driverServices.getChrome();67 DriverService driverService = serviceProperties == null ? null : serviceProperties.getDriverService();68 return driverService == null ?69 new ChromeDriver(desiredCapabilities)70 : new RemoteWebDriver(driverService.getUrl(), desiredCapabilities);71 }72 },73 FIREFOX(BrowserType.FIREFOX) {74 @Override75 public WebDriver create(WebDriverFactory webDriverFactory, DesiredCapabilities desiredCapabilities) {76 FirefoxDriverServiceProperties serviceProperties = webDriverFactory.driverServices == null ? null : webDriverFactory.driverServices.getFirefox();77 DriverService driverService = serviceProperties == null ? null : serviceProperties.getDriverService();78 FirefoxOptions firefoxOptions = new FirefoxOptions().merge(desiredCapabilities);79 return driverService == null ? new FirefoxDriver(firefoxOptions) : new RemoteWebDriver(driverService.getUrl(), firefoxOptions);80 }81 },82 IE(BrowserType.IE, BrowserType.IEXPLORE) {83 @Override84 public WebDriver create(WebDriverFactory webDriverFactory, DesiredCapabilities desiredCapabilities) {85 InternetExplorerDriverServiceProperties serviceProperties = webDriverFactory.driverServices == null ? null : webDriverFactory.driverServices.getInternetExplorer();86 DriverService driverService = serviceProperties == null ? null : serviceProperties.getDriverService();87 InternetExplorerOptions internetExplorerOptions = new InternetExplorerOptions().merge(desiredCapabilities);88 return driverService == null ? new InternetExplorerDriver(internetExplorerOptions) : new RemoteWebDriver(driverService.getUrl(), internetExplorerOptions);89 }90 },91 SAFARI(BrowserType.SAFARI) {92 @Override93 public WebDriver create(WebDriverFactory webDriverFactory, DesiredCapabilities desiredCapabilities) {94 return new SafariDriver(new SafariOptions().merge(desiredCapabilities));95 }96 };97 private Set<String> types;98 private WebDriverType(String ... types) {99 this.types = Sets.newHashSet();100 for (String type : types) {101 this.types.add(type.toLowerCase());102 }103 }104 public abstract WebDriver create(WebDriverFactory webDriverFactory, DesiredCapabilities desiredCapabilities);105 public static WebDriverType typeFor(String value) {106 value = value.toLowerCase();107 for (WebDriverType type : WebDriverType.values()) {108 if (type.types.contains(value)) return type;109 }110 throw new IllegalArgumentException(format("Type %s is not valid", value));111 }112 }113 public WebDriverFactory(DriverServicesProperties driverServices) {114 this.driverServices = driverServices;115 }116 public WebDriver create(WebDriverProperties webDriverProperties) throws IOException {117 DesiredCapabilities desiredCapabilities = new DesiredCapabilities(webDriverProperties.getDesiredCapabilities());118 desiredCapabilities.merge(browserSpecificCapabilities(webDriverProperties));119 WebDriver webDriver = null;120 if (webDriverProperties.getUrl() != null) {121 RemoteWebDriver remoteDriver = new RemoteWebDriver(webDriverProperties.getUrl(), desiredCapabilities);122 remoteDriver.setFileDetector(new LocalFileDetector());123 webDriver = remoteDriver;124 } else {125 String browserName = desiredCapabilities == null ? null : desiredCapabilities.getBrowserName();126 if (Strings.isNullOrEmpty(browserName)) browserName = BrowserType.CHROME;127 webDriver = WebDriverType.typeFor(browserName).create(this, desiredCapabilities);128 }129 WindowProperties window = webDriverProperties.getWindow();130 if (window != null) {131 DimensionProperties size = window.getSize();132 PointProperties position = window.getPosition();133 if (size != null) webDriver.manage().window().setSize(new Dimension(size.getWidth(), size.getHeight()));134 if (position != null) webDriver.manage().window().setPosition(new Point(position.getX(), position.getY()));135 if (window.isMaximized()) {136 webDriver.manage().window().maximize();137 }138 }139 webDriver = webDriver instanceof TakesScreenshot ? webDriver : new Augmenter().augment(webDriver);140 for (WebDriverTransformer transformer : driverServices.getWebDriverTranformers()) webDriver = transformer.transform(webDriver);141 return webDriverProperties.isStateful() ? new StatefulWebDriver(webDriver) : webDriver;142 }143 private Capabilities browserSpecificCapabilities(WebDriverProperties webDriverProperties) throws IOException {144 ChromeOptionsProperties chromeProperties = webDriverProperties.getChromeOptions();145 if (chromeProperties != null) return chromeCapabilities(chromeProperties);146 FirefoxProfileProperties firefoxProperties = webDriverProperties.getFirefoxProfile();147 if (firefoxProperties != null) return firefoxCapabilities(firefoxProperties);148 return new MutableCapabilities();149 }150 private Capabilities chromeCapabilities(ChromeOptionsProperties chromeProperties) {151 ChromeOptions options = new ChromeOptions();152 if (chromeProperties.getArgs() != null) options.addArguments(chromeProperties.getArgs());153 if (chromeProperties.getBinary() != null) options.setBinary(chromeProperties.getBinary());154 if (chromeProperties.getExtensions() != null) options.addExtensions(chromeProperties.getExtensions());155 if (chromeProperties.getPreferences() != null) options.setExperimentalOption("prefs", chromeProperties.getPreferences());156 if (chromeProperties.getMobileEmulation() != null) options.setExperimentalOption("mobileEmulation", chromeProperties.getMobileEmulation());157 if (chromeProperties.getLoggingPrefs() != null) options.setCapability("goog:loggingPrefs", chromeProperties.getLoggingPrefs());158 return options;159 }160 private Capabilities firefoxCapabilities(FirefoxProfileProperties firefoxProperties) throws IOException {161 File profileDirectory = null;162 String profileDir = firefoxProperties.getDir();163 if (profileDir != null) {164 profileDirectory = new File(profileDir);165 }166 FirefoxProfile profile = new FirefoxProfile(profileDirectory);167 List<PreferenceProperties> preferences = firefoxProperties.getPreferences();168 if (preferences != null) {169 for (PreferenceProperties preference : preferences) {170 switch (preference.getType()) {171 case BOOLEAN:172 profile.setPreference(preference.getName(), (Boolean) preference.getValue());173 break;174 case INTEGER:175 profile.setPreference(preference.getName(), (Integer) preference.getValue());176 break;177 case STRING:178 profile.setPreference(preference.getName(), (String) preference.getValue());179 }180 }181 }182 List<File> extensions = firefoxProperties.getExtensions();183 if (extensions != null) extensions.stream().forEach(profile::addExtension);184 profile.setAlwaysLoadNoFocusLib(firefoxProperties.shouldLoadNoFocusLib());185 profile.setAcceptUntrustedCertificates(firefoxProperties.shouldAcceptUntrustedCerts());186 profile.setAssumeUntrustedCertificateIssuer(firefoxProperties.shouldUntrustedCertIssuer());187 return new FirefoxOptions().setProfile(profile);188 }189}...
Source:BrowserDriverFunctions.java
1package org.rapidpm.frp.vaadin.addon.testbench.ng.tooling;2import static java.lang.System.setProperty;3import static org.rapidpm.frp.StringFunctions.notEmpty;4import static org.rapidpm.frp.StringFunctions.notStartsWith;5import static org.rapidpm.frp.Transformations.not;6import static org.rapidpm.frp.matcher.Case.match;7import static org.rapidpm.frp.matcher.Case.matchCase;8import static org.rapidpm.frp.model.Result.success;9import java.io.BufferedInputStream;10import java.io.File;11import java.io.FileInputStream;12import java.io.FileReader;13import java.io.IOException;14import java.net.Inet4Address;15import java.net.InetAddress;16import java.net.NetworkInterface;17import java.net.URL;18import java.util.ArrayList;19import java.util.Collection;20import java.util.Collections;21import java.util.Enumeration;22import java.util.HashMap;23import java.util.List;24import java.util.Map;25import java.util.Properties;26import java.util.function.Function;27import java.util.function.Supplier;28import java.util.stream.Collectors;29import org.openqa.selenium.Platform;30import org.openqa.selenium.WebDriver;31import org.openqa.selenium.chrome.ChromeDriver;32import org.openqa.selenium.firefox.FirefoxDriver;33import org.openqa.selenium.ie.InternetExplorerDriver;34import org.openqa.selenium.phantomjs.PhantomJSDriver;35import org.openqa.selenium.remote.BrowserType;36import org.openqa.selenium.remote.DesiredCapabilities;37import org.openqa.selenium.remote.RemoteWebDriver;38import org.openqa.selenium.safari.SafariDriver;39import org.rapidpm.frp.Transformations;40import org.rapidpm.frp.functions.CheckedExecutor;41import org.rapidpm.frp.functions.CheckedFunction;42import org.rapidpm.frp.functions.CheckedPredicate;43import org.rapidpm.frp.functions.CheckedSupplier;44import org.rapidpm.frp.matcher.Case;45import org.rapidpm.frp.model.Result;46import com.google.gson.stream.JsonReader;47import com.vaadin.testbench.TestBench;48/**49 *50 *51 */52public interface BrowserDriverFunctions {53 Supplier<String> ipSupplierLocalIP = () -> {54 final CheckedSupplier<Enumeration<NetworkInterface>> checkedSupplier = NetworkInterface::getNetworkInterfaces;55 return Transformations.<NetworkInterface>enumToStream()56 .apply(checkedSupplier.getOrElse(Collections::emptyEnumeration))57 .filter((CheckedPredicate<NetworkInterface>) NetworkInterface::isUp)58 .map(NetworkInterface::getInetAddresses)59 .flatMap(iaEnum -> Transformations.<InetAddress>enumToStream().apply(iaEnum))60 .filter(inetAddress -> inetAddress instanceof Inet4Address)61 .filter(not(InetAddress::isMulticastAddress))62 .filter(not(InetAddress::isLoopbackAddress))63 .map(InetAddress::getHostAddress)64 .filter(notEmpty())65 .filter(adr -> notStartsWith().apply(adr, "127"))66 .filter(adr -> notStartsWith().apply(adr, "169.254"))67 .filter(adr -> notStartsWith().apply(adr, "255.255.255.255"))68 .filter(adr -> notStartsWith().apply(adr, "255.255.255.255"))69 .filter(adr -> notStartsWith().apply(adr, "0.0.0.0"))70 // .filter(adr -> range(224, 240).noneMatch(nr -> adr.startsWith(valueOf(nr))))71 .findFirst().orElse("localhost");72 };73 CheckedFunction<String, Properties> readProperties = (filename) -> {74 try (75 final FileInputStream fis = new FileInputStream(new File(filename));76 final BufferedInputStream bis = new BufferedInputStream(fis)) {77 final Properties properties = new Properties();78 properties.load(bis);79 return properties;80 } catch (IOException e) {81 e.printStackTrace();82 throw e;83 }84 };85 CheckedExecutor readTestbenchProperties = () -> readProperties86 .apply("config/testbench.properties")87 .ifPresent(p -> p.forEach((key, value) -> setProperty((String) key, (String) value))88 );89 Function<String, Result<WebDriver>> localWebDriverInstance = browserType -> match(90 matchCase(() -> success(new PhantomJSDriver())),91 matchCase(browserType::isEmpty, () -> Result.failure("browserTape should not be empty")),92 matchCase(() -> browserType.equals(BrowserType.PHANTOMJS), () -> success(new PhantomJSDriver())),93 matchCase(() -> browserType.equals(BrowserType.FIREFOX), () -> success(new FirefoxDriver())),94 matchCase(() -> browserType.equals(BrowserType.CHROME), () -> success(new ChromeDriver())),95 matchCase(() -> browserType.equals(BrowserType.SAFARI), () -> success(new SafariDriver())),96 matchCase(() -> browserType.equals(BrowserType.IE), () -> success(new InternetExplorerDriver())));97 Function<String, Result<DesiredCapabilities>> desiredCapabilities = (browsertype) ->98 match(99 matchCase(() -> success(DesiredCapabilities.phantomjs())),100 matchCase(browsertype::isEmpty, () -> Result.failure("browsertype should not be empty")),101 matchCase(() -> browsertype.equals(BrowserType.PHANTOMJS), () -> success(DesiredCapabilities.phantomjs())),102 matchCase(() -> browsertype.equals(BrowserType.FIREFOX), () -> success(DesiredCapabilities.firefox())),103 matchCase(() -> browsertype.equals(BrowserType.CHROME), () -> success(DesiredCapabilities.chrome())),104 matchCase(() -> browsertype.equals(BrowserType.SAFARI), () -> success(DesiredCapabilities.safari())),105 matchCase(() -> browsertype.equals(BrowserType.IE), () -> success(DesiredCapabilities.internetExplorer())));106 Supplier<Result<List<DesiredCapabilities>>> readBrowserCombinations = () -> {107 final List<DesiredCapabilities> result = new ArrayList<>();108 final File file = new File("config/browser_combinations.json");109 try (110 final FileReader fr = new FileReader(file);111 final JsonReader reader = new JsonReader(fr)) {112 reader.beginObject();113 while (reader.hasNext()) {114 String name = reader.nextName();115 if (name.equals("browsers")) {116 reader.beginArray();117 while (reader.hasNext()) {118 reader.beginObject();119 String browser = "";120 String version = "";121 String platform = "";122 final Map<String, String> noNameProps = new HashMap<>();123 while (reader.hasNext()) {124 String property = reader.nextName();125 switch (property) {126 case "browserName":127 browser = reader.nextString();128 break;129 case "platform":130 platform = reader.nextString();131 break;132 case "version":133 version = reader.nextString();134 break;135 default:136 noNameProps.put(property, reader.nextString());137 break;138 }139 }140 //TODO remove this hack, remove while -> functional141 final String platformFinal = platform;142 final String versionFinal = version;143 final Result<DesiredCapabilities> capabilitiesResult = desiredCapabilities.apply(browser);144 capabilitiesResult.bind(145 sucess -> {146 sucess.setPlatform(Platform.fromString(platformFinal));147 sucess.setVersion(versionFinal);148 noNameProps.forEach(sucess::setCapability);149 ((CheckedExecutor) reader::endObject).execute();150 },151 failed -> {152 }153 );154 capabilitiesResult.ifPresent(result::add);155 }156 reader.endArray();157 }158 }159 reader.endObject();160 reader.close();161 } catch (IOException e) {162 e.printStackTrace();163 return Result.failure(e.getMessage());164 }165 return Result.success(result);166 };167 /**168 * This will create all defined WebDriver instances for the full integration test.169 * If you are defining different Selenium Hubs, you will get Driver for all of them.170 * Normally this amount is not so big, means that memory consumption should not be a problem171 */172 Supplier<List<WebDriver>> webDriverInstances = () -> {173 readTestbenchProperties.execute(); // load properties for locale webdriver174 final Properties properties = readProperties175 .apply("config/selenium-grids.properties")176 .getOrElse(Properties::new);177 return readBrowserCombinations178 .get()179 .getOrElse(Collections::emptyList) //TODO check if needed180 .stream()181 .map(desiredCapability -> {182 final String browserName = desiredCapability.getBrowserName();183 //for all selenium ips184 return properties185 .entrySet()186 .stream()187 .map(e -> {188 final String key = (String) e.getKey();189 final String targetAddress = (String) e.getValue();190 final String ip = (targetAddress.endsWith("locale-ip"))191 ? ipSupplierLocalIP.get()192 : targetAddress;193 return Case194 .match(195 matchCase(() -> ((CheckedSupplier<WebDriver>) () -> {196 final URL url = new URL("http://" + ip + ":4444/wd/hub");197 final RemoteWebDriver remoteWebDriver = new RemoteWebDriver(url, desiredCapability);198 return TestBench.createDriver(remoteWebDriver);199 }).get()),200 matchCase(() -> key.equals("nogrid"), () -> localWebDriverInstance.apply(browserName))201 );202 })203 .filter(Result::isPresent)204 .collect(Collectors.toList());205 })206 .flatMap(Collection::stream)207 .map(Result::get)208 .collect(Collectors.toList());209 };210}...
Source:Driver.java
1package com.webstaurantstore.utils;2import io.github.bonigarcia.wdm.WebDriverManager;3import org.openqa.selenium.Platform;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.chrome.ChromeDriver;6import org.openqa.selenium.chrome.ChromeOptions;7import org.openqa.selenium.firefox.FirefoxDriver;8import org.openqa.selenium.remote.BrowserType;9import org.openqa.selenium.remote.DesiredCapabilities;10import org.openqa.selenium.remote.RemoteWebDriver;11import java.net.URL;12public class Driver {13 private static final ThreadLocal<WebDriver> driverPool = new ThreadLocal<>();14 private Driver(){}15 public synchronized static WebDriver getDriver() {16 String GRID_URL = "http://35.171.158.59:4444/wd/hub";17 if (driverPool.get() == null) {18 String browser = ConfigsReader.getProperty("browser").toLowerCase();19 if (System.getProperty("browser") != null) {20 browser = System.getProperty("browser");21 }22 if (System.getProperty("grid_url") != null) {23 GRID_URL = System.getProperty("grid_url");24 }25 switch (browser) {26 case "chrome":27 WebDriverManager.chromedriver().setup();28 ChromeOptions chromeOptions = new ChromeOptions();29 chromeOptions.addArguments("--start-maximized");30 driverPool.set(new ChromeDriver(chromeOptions));31 break;32 case "chromeheadless":33 //to run chrome without interface (headless mode)34 WebDriverManager.chromedriver().setup();35 ChromeOptions options = new ChromeOptions();36 options.setHeadless(true);37 driverPool.set(new ChromeDriver(options));38 break;39 case "chrome-remote":40 try {41 URL url = new URL(GRID_URL);42 DesiredCapabilities desiredCapabilities = new DesiredCapabilities();43 desiredCapabilities.setBrowserName(BrowserType.CHROME);44 desiredCapabilities.setPlatform(Platform.ANY);45 driverPool.set(new RemoteWebDriver(url, desiredCapabilities));46 } catch (Exception e) {47 e.printStackTrace();48 }49 break;50 case "firefox-remote":51 try {52 URL url = new URL(GRID_URL);53 DesiredCapabilities desiredCapabilities = new DesiredCapabilities();54 desiredCapabilities.setBrowserName(BrowserType.FIREFOX);55 desiredCapabilities.setPlatform(Platform.ANY);56 driverPool.set(new RemoteWebDriver(url, desiredCapabilities));57 } catch (Exception e) {58 e.printStackTrace();59 }60 break;61 case "firefox":62 WebDriverManager.firefoxdriver().setup();63 driverPool.set(new FirefoxDriver());64 break;65 default:66 throw new RuntimeException("Wrong browser name!");67 }68 }69 return driverPool.get();70 }71 public static void closeDriver() {72 if (driverPool.get() != null) {73 driverPool.get().quit();74 driverPool.remove();75 }76 }77}...
Source:BrowserLaunching.java
1package com.utility;2import java.util.Hashtable;3import java.util.Map;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.chrome.ChromeDriver;6import org.openqa.selenium.chrome.ChromeOptions;7import org.openqa.selenium.firefox.FirefoxDriver;8import org.openqa.selenium.ie.InternetExplorerDriver;9import org.openqa.selenium.remote.CapabilityType;10import org.openqa.selenium.remote.DesiredCapabilities;11import org.testng.Reporter;12public class BrowserLaunching extends CommonLib implements GlobalVariable13{14 //-------------------------browser driver Keys and browser driver paths declaration----------------15 static String chromeDriverKey ="webdriver.chrome.driver";16 static String chromeDriverPath = "C:\\ILFS\\NRDA\\workspace\\NRDA_FRAMEWORK\\NRDA_PROJECT\\src\\main\\resources\\chromedriver2.exe";17 static String IE_DriverKey ="webdriver.ie.driver";18 static String IE_DriverPath = "C:\\ILFS\\NRDA\\workspace\\NRDA_FRAMEWORK\\NRDA_PROJECT\\src\\main\\resources\\IEDriverServer.exe";19 static String firefoxDriverKey ="webdriver.gecko.driver";20 static String firefoxDriverPath = "C:\\ILFS\\NRDA\\workspace\\NRDA_FRAMEWORK\\NRDA_PROJECT\\src\\main\\resources\\geckodriver.exe";21 static String DownloadPDF="C:\\ILFS\\NRDA\\workspace\\NRDA_FRAMEWORK\\NRDA_PROJECT\\DownloadFile";22 //-------------------------------------------------------------------------------------------------23 /***********************************************************************************************************************************/24 /*25 * getbrowser() is used to get the browser instance form the constant26 * interface and launch according to the defined variable name in the27 * Constant interface28 * @param browser29 * @return 30 * @author deepak.saini31 * @since 2020-02-2632 */33 /************************************************************************************************************************************/34 @SuppressWarnings("deprecation")35 public static WebDriver getBrowser(String browsertype)36 { 37 switch (browsertype)38 {39 case "firefox":40 System.setProperty(firefoxDriverKey, firefoxDriverPath);41 driver=new FirefoxDriver();42 deleteAllCookies();43 windowMaximize();44 break;45 /*46 * Map Interface is used to handle the browser pop up notification47 */48 49 case "chrome":50 Map<String,Object> chromepref=new Hashtable<String,Object>();51 chromepref.put("profile.default_content_settings.popups", 0);52 chromepref.put("download.prompt_for_download", "false");53 chromepref.put("download.default_directory",DownloadPDF);54 55 ChromeOptions options=new ChromeOptions();56 options.setExperimentalOption("prefs",chromepref);57 58 DesiredCapabilities capability=DesiredCapabilities.chrome();59 capability.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);60 capability.setCapability(ChromeOptions.CAPABILITY,options);61 System.setProperty(chromeDriverKey,chromeDriverPath);62 driver= new ChromeDriver(capability);63 64 65 /*System.setProperty(chromeDriverKey, chromeDriverPath);66 driver = new ChromeDriver();67 deleteAllCookies();*/68 windowMaximize();69 break;70 case "IE":71 System.setProperty(IE_DriverKey, IE_DriverPath);72 driver=new InternetExplorerDriver();73 deleteAllCookies();74 windowMaximize();75 break;76 default:77 Reporter.log("browser : " + browsertype + " is invalid, Launching Chrome as browser of choice..");78 driver = new ChromeDriver();79 }80 return driver;81 }82}...
Source:BrowserDriver.java
1package GenericLibrary;2import java.util.Hashtable;3import java.util.Map;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.chrome.ChromeDriver;6import org.openqa.selenium.chrome.ChromeOptions;7import org.openqa.selenium.firefox.FirefoxDriver;8import org.openqa.selenium.ie.InternetExplorerDriver;9import org.openqa.selenium.remote.CapabilityType;10import org.openqa.selenium.remote.DesiredCapabilities;11import org.testng.Reporter;12/**13 * @author deepak.saini14 *15 */16public class BrowserDriver extends CommonLibrary implements ConstantI17{18 //-------------------------browser driver Keys and browser driver paths declaration----------------19 static String chromeDriverKey ="webdriver.chrome.driver";20 static String chromeDriverPath = "C:\\ILFS\\NRDA\\workspace\\NRDA_FRAMEWORK\\NRDA_PROJECT\\src\\main\\resources\\chromedriver2.exe";21 static String IE_DriverKey ="webdriver.ie.driver";22 static String IE_DriverPath = "C:\\ILFS\\NRDA\\workspace\\NRDA_FRAMEWORK\\NRDA_PROJECT\\src\\main\\resources\\IEDriverServer.exe";23 static String firefoxDriverKey ="webdriver.gecko.driver";24 static String firefoxDriverPath = "C:\\ILFS\\NRDA\\workspace\\NRDA_FRAMEWORK\\NRDA_PROJECT\\src\\main\\resources\\geckodriver.exe";25 static String DownloadPDF="C:\\ILFS\\NRDA\\workspace\\NRDA_FRAMEWORK\\NRDA_PROJECT\\DownloadFile";26 //-------------------------------------------------------------------------------------------------27 /***********************************************************************************************************************************/28 /*29 * getbrowser() is used to get the browser instance form the constant interface30 * and launch according to the defined variable name in the Constant interface31 * @param browser32 * @return33 * @author deepak.saini34 * @since 2017-06-1435 */36 /************************************************************************************************************************************/37 public static WebDriver getBrowser(String browsertype)38 { 39 switch (browsertype)40 {41 case "firefox":42 System.setProperty(firefoxDriverKey, firefoxDriverPath);43 driver=new FirefoxDriver();44 deleteAllCookies();45 windowMaximize();46 break;47 /*48 * Map Interface is used to handle the browser pop up notification49 */50 51 case "chrome":52 Map<String,Object> chromepref=new Hashtable<String,Object>();53 chromepref.put("profile.default_content_settings.popups", 0);54 chromepref.put("download.prompt_for_download", "false");55 chromepref.put("download.default_directory",DownloadPDF);56 57 ChromeOptions options=new ChromeOptions();58 options.setExperimentalOption("prefs",chromepref);59 60 DesiredCapabilities capability=DesiredCapabilities.chrome();61 capability.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);62 capability.setCapability(ChromeOptions.CAPABILITY,options);63 System.setProperty(chromeDriverKey,chromeDriverPath);64 driver= new ChromeDriver(capability);65 66 67 /*System.setProperty(chromeDriverKey, chromeDriverPath);68 driver = new ChromeDriver();69 deleteAllCookies();*/70 windowMaximize();71 break;72 case "IE":73 System.setProperty(IE_DriverKey, IE_DriverPath);74 driver=new InternetExplorerDriver();75 deleteAllCookies();76 windowMaximize();77 break;78 default:79 Reporter.log("browser : " + browsertype + " is invalid, Launching Chrome as browser of choice..");80 driver = new ChromeDriver();81 }82 return driver;83 }84}...
Source:DriverFactory.java
1package ru.stqa.selenium.legrc.runner;2import com.google.common.collect.ImmutableMap;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.chrome.ChromeDriver;5import org.openqa.selenium.chrome.ChromeDriverService;6import org.openqa.selenium.firefox.*;7import org.openqa.selenium.ie.InternetExplorerDriver;8import org.openqa.selenium.ie.InternetExplorerDriverService;9import org.openqa.selenium.remote.BrowserType;10import org.openqa.selenium.remote.RemoteWebDriver;11import java.io.File;12import java.io.IOException;13import java.net.URL;14import java.util.Map;15public class DriverFactory {16 private CliOptions options;17 public DriverFactory(CliOptions options) {18 this.options = options;19 }20 public WebDriver createDriver() throws IOException {21 if (options.gridUrl == null) {22 // local driver23 DriverSupplier supplier = driverSuppliers.get(options.browser);24 if (supplier == null) {25 throw new IllegalArgumentException("Unrecognized browser: " + options.browser);26 }27 return supplier.getDriver(options);28 } else {29 // remote driver30 return new RemoteWebDriver(new URL(options.gridUrl), options.getCapabilities());31 }32 }33 private interface DriverSupplier {34 WebDriver getDriver(CliOptions options);35 }36 private Map<String, DriverSupplier> driverSuppliers = new ImmutableMap.Builder<String, DriverSupplier>()37 .put(BrowserType.FIREFOX, new DriverSupplier() {38 @Override39 public WebDriver getDriver(CliOptions options) {40 FirefoxBinary binary = options.executable == null ? new FirefoxBinary()41 : new FirefoxBinary(new File(options.executable));42 return new FirefoxDriver(binary, new FirefoxProfile(), options.getCapabilities());43 }44 })45 .put("marionette", new DriverSupplier() {46 @Override47 public WebDriver getDriver(CliOptions options) {48 GeckoDriverService.Builder serviceBuilder = new GeckoDriverService.Builder();49 if (options.driverExe != null) {50 serviceBuilder.usingDriverExecutable(new File(options.driverExe));51 }52 return new MarionetteDriver(serviceBuilder.build(), options.getCapabilities());53 }54 })55 .put(BrowserType.CHROME, new DriverSupplier() {56 @Override57 public WebDriver getDriver(CliOptions options) {58 ChromeDriverService.Builder serviceBuilder = new ChromeDriverService.Builder();59 if (options.driverExe != null) {60 serviceBuilder.usingDriverExecutable(new File(options.driverExe));61 }62 return new ChromeDriver(serviceBuilder.build(), options.getCapabilities());63 }64 })65 .put(BrowserType.IE, new DriverSupplier() {66 @Override67 public WebDriver getDriver(CliOptions options) {68 InternetExplorerDriverService.Builder serviceBuilder = new InternetExplorerDriverService.Builder();69 if (options.driverExe != null) {70 serviceBuilder.usingDriverExecutable(new File(options.driverExe));71 }72 return new InternetExplorerDriver(serviceBuilder.build(), options.getCapabilities());73 }74 })75 .build();76}...
Source:DriverManagerOfChrome.java
1package com.avin.networks.at.pom.factories.driver;2import java.net.MalformedURLException;3import java.net.URL;4import org.openqa.selenium.PageLoadStrategy;5import org.openqa.selenium.WebDriver;6import org.openqa.selenium.chrome.ChromeDriver;7import org.openqa.selenium.chrome.ChromeOptions;8import org.openqa.selenium.devtools.DevTools;9import org.openqa.selenium.devtools.v96.security.Security;10import org.openqa.selenium.remote.BrowserType;11import org.openqa.selenium.remote.DesiredCapabilities;12import org.openqa.selenium.remote.RemoteWebDriver;13import com.avin.networks.at.config.enums.ConfigProperties;14import com.avin.networks.at.utility.PropertitesUtils;15import io.github.bonigarcia.wdm.WebDriverManager;16@SuppressWarnings("deprecation")17public class DriverManagerOfChrome implements DriverInterface{18 String runmode = PropertitesUtils.get(ConfigProperties.RUNMODE);19 20 @Override21 public WebDriver createDriver() {22 RemoteWebDriver driver = null;23 try {24 if (runmode.equalsIgnoreCase("remote")) {25 ChromeOptions opt = new ChromeOptions();26 opt.setPageLoadStrategy(PageLoadStrategy.EAGER);27 28 DesiredCapabilities cap = new DesiredCapabilities();29 cap.setBrowserName(BrowserType.CHROME);30 driver = new RemoteWebDriver(new URL(""), cap);31 32 DevTools devTools = ((ChromeDriver) driver).getDevTools();33 devTools.createSession();34 devTools.send(Security.enable());35 devTools.send(Security.setIgnoreCertificateErrors(true));36 37 driver.manage().window().maximize();38 driver.manage().deleteAllCookies();39 40 } else {41 ChromeOptions opt = new ChromeOptions();42 opt.setPageLoadStrategy(PageLoadStrategy.EAGER);43 44 WebDriverManager.chromedriver().clearDriverCache();45 WebDriverManager.chromedriver().setup();46 driver = new ChromeDriver();47 48 DevTools devTools = ((ChromeDriver) driver).getDevTools();49 devTools.createSession();50 devTools.send(Security.enable());51 devTools.send(Security.setIgnoreCertificateErrors(true)); 52 53 driver.manage().window().maximize();54 driver.manage().deleteAllCookies();55 }56 } catch (MalformedURLException e) {57 e.printStackTrace();58 }59 return driver;60 }61 62}...
Source:BrowserType.java
1/*2 Copyright 2014 Red Hat, Inc. and/or its affiliates.3 This file is part of darcy-webdriver.4 This program is free software: you can redistribute it and/or modify5 it under the terms of the GNU General Public License as published by6 the Free Software Foundation, either version 3 of the License, or7 (at your option) any later version.8 This program is distributed in the hope that it will be useful,9 but WITHOUT ANY WARRANTY; without even the implied warranty of10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the11 GNU General Public License for more details.12 You should have received a copy of the GNU General Public License13 along with this program. If not, see <http://www.gnu.org/licenses/>.14 */15package com.redhat.darcy.webdriver.guice;16import com.redhat.darcy.web.api.BrowserFactory;17import org.openqa.selenium.remote.DesiredCapabilities;18public interface BrowserType {19 /**20 * Used for configuring a remote driver to use this browser.21 * @return A {@link org.openqa.selenium.remote.DesiredCapabilities} object that requests the22 * browser type.23 */24 DesiredCapabilities asCapability();25 /**26 * Used for launching a local browser.27 * @return A {@link com.redhat.darcy.web.api.BrowserFactory} that instantiates browsers of the28 * browser type.29 */30 BrowserFactory asBrowserFactory();31}...
Interface BrowserType
Using AI Code Generation
1import org.openqa.selenium.remote.BrowserType;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.chrome.ChromeDriver;4import org.openqa.selenium.firefox.FirefoxDriver;5import org.openqa.selenium.ie.InternetExplorerDriver;6import org.openqa.selenium.edge.EdgeDriver;7import org.openqa.selenium.safari.SafariDriver;8import org.openqa.selenium.opera.OperaDriver;9import org.openqa.selenium.opera.OperaOptions;10import org.openqa.selenium.opera.OperaOptions;11import org.openqa.selenium.opera.OperaDriver;12import org.openqa.selenium.opera.OperaOptions;13import org.openqa.selenium.opera.OperaDriver;14import org.openqa.selenium.opera.OperaOptions;15import org.openqa.selenium.opera.OperaDriver;16import org.openqa.selenium.opera.OperaOptions;17import org.openqa.selenium.opera.OperaDriver;18import org.openqa.selenium.opera.OperaOptions;19import org.openqa.selenium.opera.OperaDriver;20import org.openqa.selenium.opera.OperaOptions;
Interface BrowserType
Using AI Code Generation
1import org.openqa.selenium.remote.BrowserType;2import org.openqa.selenium.remote.DesiredCapabilities;3DesiredCapabilities capabilities = DesiredCapabilities.chrome();4capabilities.setCapability(CapabilityType.BROWSER_NAME, BrowserType.CHROME);5capabilities.setCapability(CapabilityType.PLATFORM_NAME, Platform.WINDOWS);6capabilities.setCapability(CapabilityType.VERSION, "61.0");7capabilities.setCapability("enableVNC", true);8capabilities.setCapability("screenResolution", "1280x1024x24");9driver.quit();10 (unknown error: DevToolsActivePort file doesn't exist)11 (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)12 (Driver info: chromedriver=2.31.488774 (6a0c1e1d6b8a0a8d9e9c7f2f1b1d7b8e0b0a7b1a),platform=Linux 3.13.0-107-generic x86_64) (WARNING: The server did not provide any stacktrace information)
Interface BrowserType
Using AI Code Generation
1import org.openqa.selenium.remote.BrowserType;2public class BrowserTypeEx {3public static void main(String[] args) {4System.out.println(BrowserType.CHROME);5System.out.println(BrowserType.FIREFOX);6System.out.println(BrowserType.IE);7System.out.println(BrowserType.IE_HTA);8System.out.println(BrowserType.IEXPLORE);9System.out.println(BrowserType.IEXPLORE_PROXY);10System.out.println(BrowserType.OPERA);11System.out.println(BrowserType.OPERA_BLINK);12System.out.println(BrowserType.OPERA_JAVA);13System.out.println(BrowserType.SAFARI);14}15}16import org.openqa.selenium.remote.CapabilityType;17public class CapabilityTypeEx {18public static void main(String[] args) {19System.out.println(CapabilityType.ACCEPT_SSL_CERTS);20System.out.println(CapabilityType.BROWSER_NAME);21System.out.println(CapabilityType.HAS_NATIVE_EVENTS);22System.out.println(CapabilityType.JAVASCRIPT_ENABLED);23System.out.println(CapabilityType.LOGGING_PREFS);24System.out.println(CapabilityType.NATIVE_EVENTS);25System.out.println(CapabilityType.PAGE_LOAD_STRATEGY);26System.out.println(CapabilityType.PLATFORM);27System.out.println(CapabilityType.PROXY);28System.out.println(CapabilityType.SUPPORTS_ALERTS);29System.out.println(CapabilityType.SUPPORTS_APPLICATION_CACHE);30System.out.println(CapabilityType.SUPPORTS_FINDING_BY_CSS);31System.out.println(CapabilityType.SUPPORTS_JAVASCRIPT);32System.out.println(CapabilityType.SUPPORTS_LOCATION_CONTEXT);33System.out.println(CapabilityType.SUPPORTS_SQL_DATABASE);34System.out.println(CapabilityType.SUPPORTS_WEB_STORAGE);35System.out.println(CapabilityType.TAKES_SCREENSHOT);36System.out.println(CapabilityType.VERSION);37System.out.println(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR);38}39}
Interface BrowserType
Using AI Code Generation
1WebDriver driver = new ChromeDriver();2BrowserType browserType = ((HasCapabilities) driver).getCapabilities().getBrowserName();3System.out.println(browserType);4WebDriver driver = new ChromeDriver();5BrowserType browserType = ((HasCapabilities) driver).getCapabilities().getBrowserName();6System.out.println(browserType);
LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.
Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.
What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.
Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.
Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.
How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.
Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.
Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.
LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.
Get 100 minutes of automation test minutes FREE!!