Example usage for org.openqa.selenium.chrome ChromeDriver ChromeDriver

List of usage examples for org.openqa.selenium.chrome ChromeDriver ChromeDriver

Introduction

In this page you can find the example usage for org.openqa.selenium.chrome ChromeDriver ChromeDriver.

Prototype

public ChromeDriver(ChromeOptions options) 

Source Link

Document

Creates a new ChromeDriver instance with the specified options.

Usage

From source file:de.ppi.selenium.browser.DefaultWebDriverFactory.java

License:Apache License

@Override
public WebDriver createWebDriver(Map<String, String> options, DesiredCapabilities capabilities)
        throws IOException {
    ClientProperties properties = new ClientProperties(options.get(CLIENT_PROPERTIES_KEY));

    WebDriver wd = null;//from   w w  w  . j ava2  s. c  o m
    DesiredCapabilities desiredCapabilities = new DesiredCapabilities(capabilities);
    String browser = properties.getBrowser();

    if (properties.isUseGrid()) {
        RemoteWebDriver remoteWebDriver = new RemoteWebDriver(new URL(properties.getGridUrl()), capabilities);
        remoteWebDriver.setFileDetector(new LocalFileDetector());
        wd = remoteWebDriver;
    } else {
        if (browser == null || browser.equals("")) {
            throw new RuntimeException(
                    "Browser cannot be null. Please set 'browser' in client properties. Supported browser types: IE, Firefox, Chrome, Safari, HtmlUnit.");
        } else if (browser.equalsIgnoreCase("ie") || browser.equalsIgnoreCase("iexplore")
                || browser.equalsIgnoreCase("*iexplore")) {
            String webdriverIEDriver = properties.getWebDriverIEDriver();

            if (webdriverIEDriver != null) {
                System.setProperty("webdriver.ie.driver", webdriverIEDriver);
            }

            String browserVersion = properties.getBrowserVersion();

            if (browserVersion == null || browserVersion.equals("")) {
                throw new RuntimeException(
                        "When using IE as the browser, please set 'browser.version' in client properties");
            } else {
                if (browserVersion.startsWith("9")) {
                    desiredCapabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
                    desiredCapabilities.setCapability(
                            InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
                    wd = new InternetExplorerDriver(desiredCapabilities);
                } else {
                    wd = new InternetExplorerDriver(desiredCapabilities);
                }
            }
        } else if ((browser.equalsIgnoreCase("firefox") || browser.equalsIgnoreCase("*firefox"))) {
            final String ffProfileFolder = properties.getFirefoxProfileFolder();
            final String ffProfileFile = properties.getFirefoxProfileFile();
            final String path = properties.getFfBinaryPath();
            final FirefoxProfile ffp;
            if (ffProfileFolder != null) {
                ffp = new FirefoxProfile(new File(ffProfileFolder));
            } else {
                ffp = new FirefoxProfile();
            }

            if (ffProfileFile != null) {
                addPreferences(ffp, ffProfileFile);
            }

            addPreferences(ffp, properties);

            List<String> ffExtensions = properties.getFirefoxExtensions();
            if (ffExtensions != null && ffExtensions.size() > 0) {
                addExtensionsToFirefoxProfile(ffp, ffExtensions);
            }

            if (path != null) {
                FirefoxBinary fireFox = getFFBinary(path);
                wd = new FirefoxDriver(fireFox, ffp, desiredCapabilities);
            } else {
                wd = new FirefoxDriver(new FirefoxBinary(), ffp, desiredCapabilities);

            }
        } else if (browser.equalsIgnoreCase("chrome")) {

            final String webdriverChromeDriver = properties.getWebDriverChromeDriver();

            if (webdriverChromeDriver != null) {
                System.setProperty("webdriver.chrome.driver", webdriverChromeDriver);
            }

            final ChromeOptions chromeOptions = new ChromeOptions();
            final String chromeBinaryPath = properties.getChromeBinaryPath();
            if (chromeBinaryPath != null) {
                chromeOptions.setBinary(chromeBinaryPath);
            }

            if (properties.getAcceptedLanguages() != null) {

                final Map<String, Object> prefs = new HashMap<String, Object>();
                prefs.put("intl.accept_languages", properties.getAcceptedLanguages());
                chromeOptions.setExperimentalOption("prefs", prefs);
            }
            desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);

            wd = new ChromeDriver(desiredCapabilities);

        } else if (browser.equalsIgnoreCase("safari")) {
            wd = new SafariDriver(desiredCapabilities);
        } else if (browser.equalsIgnoreCase("htmlunit")) {
            final BrowserVersion browserVersion = BrowserVersion.FIREFOX_45;
            if (properties.getAcceptedLanguages() != null) {
                browserVersion.setBrowserLanguage(properties.getAcceptedLanguages().split(",")[0]);
            }
            wd = new HtmlUnitDriver(browserVersion);
            ((HtmlUnitDriver) wd).setJavascriptEnabled(true);
        } else if (browser.equalsIgnoreCase("phantomjs")) {
            final String webdriverPhantomJSDriver = properties.getWebDriverPhantomJSDriver();
            if (properties.getAcceptedLanguages() != null) {
                desiredCapabilities.setCapability("phantomjs.page.customHeaders.Accept-Language",
                        properties.getAcceptedLanguages());
            }

            if (webdriverPhantomJSDriver != null) {
                desiredCapabilities.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
                        webdriverPhantomJSDriver);
                wd = new PhantomJSDriver(desiredCapabilities);
            } else {
                wd = new PhantomJSDriver(ResolvingPhantomJSDriverService.createDefaultService(),
                        desiredCapabilities);
            }
        } else {
            throw new IllegalArgumentException("Unsupported browser type: " + browser
                    + ". Supported browser types: IE, Firefox, Chrome, Safari, HtmlUnit, phantomjs.");
        }

        // move browser windows to specific position. It's useful for
        // debugging...
        final int browserInitPositionX = properties.getBrowserInitPositionX();
        final int browserInitPositionY = properties.getBrowserInitPositionY();
        if (browserInitPositionX != 0 || browserInitPositionY != 0) {
            wd.manage().window().setSize(new Dimension(1280, 1024));
            wd.manage().window().setPosition(new Point(browserInitPositionX, browserInitPositionY));
        }
        wd.manage().timeouts().implicitlyWait(properties.getAppearWaitTime(), TimeUnit.MILLISECONDS);
    }

    return wd;
}

From source file:edu.samplu.common.WebDriverUtil.java

License:Educational Community License

/**
 * remote.public.driver set to chrome or firefox (null assumes firefox)
 * if remote.public.hub is set a RemoteWebDriver is created (Selenium Grid)
 * if proxy.host is set, the web driver is setup to use a proxy
 * @return WebDriver or null if unable to create
 *//*from   w ww.ja  v a2s . co m*/
public static WebDriver getWebDriver() {
    String driverParam = System.getProperty(ITUtil.HUB_DRIVER_PROPERTY);
    String hubParam = System.getProperty(ITUtil.HUB_PROPERTY);
    String proxyParam = System.getProperty(PROXY_HOST_PROPERTY);

    // setup proxy if specified as VM Arg
    DesiredCapabilities capabilities = new DesiredCapabilities();
    WebDriver webDriver = null;
    if (StringUtils.isNotEmpty(proxyParam)) {
        capabilities.setCapability(CapabilityType.PROXY, new Proxy().setHttpProxy(proxyParam));
    }

    if (hubParam == null) {
        if (driverParam == null || "firefox".equalsIgnoreCase(driverParam)) {
            FirefoxProfile profile = new FirefoxProfile();
            profile.setEnableNativeEvents(false);
            capabilities.setCapability(FirefoxDriver.PROFILE, profile);
            return new FirefoxDriver(capabilities);
        } else if ("chrome".equalsIgnoreCase(driverParam)) {
            return new ChromeDriver(capabilities);
        } else if ("safari".equals(driverParam)) {
            System.out.println("SafariDriver probably won't work, if it does please contact Erik M.");
            return new SafariDriver(capabilities);
        }
    } else {
        try {
            if (driverParam == null || "firefox".equalsIgnoreCase(driverParam)) {
                return new RemoteWebDriver(new URL(ITUtil.getHubUrlString()), DesiredCapabilities.firefox());
            } else if ("chrome".equalsIgnoreCase(driverParam)) {
                return new RemoteWebDriver(new URL(ITUtil.getHubUrlString()), DesiredCapabilities.chrome());
            }
        } catch (MalformedURLException mue) {
            System.out.println(ITUtil.getHubUrlString() + " " + mue.getMessage());
            mue.printStackTrace();
        }
    }
    return null;
}

From source file:executar.Executar.java

@Override
public void run() {

    try {//  www  .  j  a va 2  s  . c  om

        System.setProperty("webdriver.chrome.driver", "C:\\AutomatedTestsDA\\chromedriver.exe");
        System.setProperty("webdriver.gecko.driver", "C:\\AutomatedTestsDA\\geckodriver.exe");

        DesiredCapabilities capabilities = DesiredCapabilities.chrome();
        capabilities.setCapability("marionette", true);
        driver = new ChromeDriver(capabilities);
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);

        for (RoteiroTeste r : listagemRoteiros) {
            new ExecutarRoteiro(r, driver).executar();
        }
    } catch (Exception ex) {
        new Slack().sendMsgExecucaoIniciada("Erro na execuo da monitoria", ex.getMessage());
    } finally {
        try {
            new Logout(driver).realizarLogout();
            Thread.sleep(5000);
        } catch (Exception ex) {
            Logger.getLogger(Executar.class.getName()).log(Level.SEVERE, null, ex);
        }
        driver.close();
        driver.quit();
    }
}

From source file:facebookfriendsoffriends.FacebookFriendsOfFriends.java

/**
 * @param args the command line arguments
 *//* w ww . jav  a 2 s . c  om*/
public FacebookFriendsOfFriends(String userName, String password) {
    this.userName = userName;
    this.password = password;
    this.facebookUrl = "https://www.facebook.com";

    this.options = new ChromeOptions();
    options.addArguments("--start-maximized");
    options.addArguments("--disable-web-security");
    options.addArguments("--no-proxy-server");
    Map<String, Object> prefs = new HashMap<String, Object>();
    prefs.put("credentials_enable_service", false);
    prefs.put("profile.password_manager_enabled", false);
    options.setExperimentalOption("prefs", prefs);
    options.addExtensions(new File(
            "/home/cbrom/.config/google-chrome/Default/Extensions/mjnbclmflcpookeapghfhapeffmpodij/1.3.0_0.crx"));
    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setCapability(ChromeOptions.CAPABILITY, options);
    this.driver = new ChromeDriver(capabilities);
}

From source file:fr.jetoile.demo.breizhcamp.webapp.driver.WebDriverFactory.java

License:Apache License

private static WebDriver chromeDriver(DesiredCapabilities capabilities) {
    System.setProperty("webdriver.chrome.driver",
            (String) capabilities.getCapability("webdriver.chrome.driver"));
    return new ChromeDriver(capabilities);
}

From source file:Interfaz.JFPrincipal.java

/**
 * Creates new form JFPrincipal/* w  w w  .  j  av a 2s  .c o m*/
 */
public JFPrincipal() {

    // Optional, if not specified, WebDriver will search your path for chromedriver.
    System.setProperty("webdriver.chrome.driver", "C:\\SeleniumDrivers\\chromedriver.exe");

    //Hacemos la ventana de chrome grande
    ChromeOptions options = new ChromeOptions();
    options.addArguments("--start-maximized");

    driverFull = new ChromeDriver(options);
    initComponents();
    this.setIconImage(new ImageIcon(getClass().getResource("/img/ikariam.png")).getImage());
    JPLogin jpLogin = new JPLogin();
    this.setBounds(100, 500, 700, 370);
    this.getContentPane().add(jpLogin);
}

From source file:io.atlasmap.standalone.E2ETest.java

License:Apache License

@Before
public void before() {
    String driverPath = System.getProperty("webdriver.chrome.driver");
    assumeTrue(driverPath != null && !driverPath.isEmpty());

    ChromeOptions options = new ChromeOptions();
    options.addArguments("--headless", "--disable-gpu", "--no-sandbox", "--disable-setuid-sandbox");
    driver = new ChromeDriver(options);
}

From source file:io.ddavison.conductor.Locomotive.java

License:Open Source License

public Locomotive() {
    final Properties props = new Properties();
    try {//from   ww w.j a va  2 s  .  co m
        props.load(getClass().getResourceAsStream("/default.properties"));
    } catch (IOException e) {
        logFatal("Couldn't load in default properties");
    } catch (Exception e) {
    }

    /**
     * Order of overrides:
     * <ol>
     *     <li>Test</li>
     *     <li>JVM Arguments</li>
     *     <li>Default properties</li>
     * </ol>
     */
    final Config testConfiguration = getClass().getAnnotation(Config.class);

    configuration = new LocomotiveConfig(testConfiguration, props);

    DesiredCapabilities capabilities;

    Capabilities extraCapabilities;
    try {
        extraCapabilities = configuration.capabilities().newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        e.printStackTrace();
        logFatal(e.getMessage());
        System.exit(1);
        return;
    }

    baseUrl = configuration.url();

    log.debug(String.format(
            "\n=== Configuration ===\n" + "\tURL:     %s\n" + "\tBrowser: %s\n" + "\tHub:     %s\n"
                    + "\tBase url: %s\n",
            configuration.url(), configuration.browser().moniker, configuration.hub(),
            configuration.baseUrl()));

    boolean isLocal = StringUtils.isEmpty(configuration.hub());

    switch (configuration.browser()) {
    case CHROME:
        capabilities = DesiredCapabilities.chrome();
        capabilities.merge(extraCapabilities);
        if (isLocal)
            try {
                driver = new ChromeDriver(capabilities);
            } catch (Exception x) {
                x.printStackTrace();
                logFatal(
                        "Also see https://github.com/conductor-framework/conductor/wiki/WebDriver-Executables");
                System.exit(1);
            }
        break;
    case FIREFOX:
        capabilities = DesiredCapabilities.firefox();
        capabilities.merge(extraCapabilities);
        if (isLocal)
            try {
                driver = new FirefoxDriver(capabilities);
            } catch (Exception x) {
                x.printStackTrace();
                logFatal(
                        "Also see https://github.com/conductor-framework/conductor/wiki/WebDriver-Executables");
                System.exit(1);
            }
        break;
    case INTERNET_EXPLORER:
        capabilities = DesiredCapabilities.internetExplorer();
        capabilities.merge(extraCapabilities);
        if (isLocal)
            try {
                driver = new InternetExplorerDriver(capabilities);
            } catch (Exception x) {
                x.printStackTrace();
                logFatal(
                        "Also see https://github.com/conductor-framework/conductor/wiki/WebDriver-Executables");
                System.exit(1);
            }
        break;
    case EDGE:
        capabilities = DesiredCapabilities.edge();
        capabilities.merge(extraCapabilities);
        if (isLocal)
            try {
                driver = new EdgeDriver(capabilities);
            } catch (Exception x) {
                x.printStackTrace();
                logFatal(
                        "Also see https://github.com/conductor-framework/conductor/wiki/WebDriver-Executables");
                System.exit(1);
            }
        break;
    case SAFARI:
        capabilities = DesiredCapabilities.safari();
        capabilities.merge(extraCapabilities);
        if (isLocal)
            try {
                driver = new SafariDriver(capabilities);
            } catch (Exception x) {
                x.printStackTrace();
                logFatal(
                        "Also see https://github.com/conductor-framework/conductor/wiki/WebDriver-Executables");
                System.exit(1);
            }
        break;
    case PHANTOMJS:
        capabilities = DesiredCapabilities.phantomjs();
        capabilities.merge(extraCapabilities);
        if (isLocal)
            try {
                driver = new PhantomJSDriver(capabilities);
            } catch (Exception x) {
                x.printStackTrace();
                logFatal(
                        "Also see https://github.com/conductor-framework/conductor/wiki/WebDriver-Executables");
                System.exit(1);
            }
        break;
    default:
        System.err.println("Unknown browser: " + configuration.browser());
        return;
    }

    if (!isLocal)
        // they are using a hub.
        try {
            capabilities.merge(extraCapabilities);
            driver = new RemoteWebDriver(new URL(configuration.hub()), capabilities); // just override the driver.
        } catch (Exception x) {
            logFatal("Couldn't connect to hub: " + configuration.hub());
            x.printStackTrace();
            return;
        }

    actions = new Actions(driver);

    if (StringUtils.isNotEmpty(baseUrl))
        driver.navigate().to(baseUrl);
}

From source file:io.github.bonigarcia.wdm.test.ChromeHeadlessTest.java

License:Apache License

@Before
public void setupTest() {
    ChromeOptions options = new ChromeOptions();
    // Tested in Google Chrome 59 on Linux. More info on:
    // https://developers.google.com/web/updates/2017/04/headless-chrome
    options.addArguments("--headless");
    options.addArguments("--disable-gpu");
    driver = new ChromeDriver(options);
}

From source file:io.github.bonigarcia.wdm.test.StabilityTest.java

License:Apache License

@Test
public void test() throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(NUM_THREADS);
    ExecutorService executorService = newFixedThreadPool(NUM_THREADS);

    for (int i = 0; i < NUM_THREADS; i++) {
        executorService.submit(() -> {
            try {
                WebDriverManager.chromedriver().setup();
                ChromeOptions options = new ChromeOptions();
                options.addArguments("--headless");
                WebDriver driver = new ChromeDriver(options);
                driver.get("https://bonigarcia.github.io/selenium-jupiter/");
                String title = driver.getTitle();
                System.out.println(title);
                driver.quit();//ww  w  . j  a  va 2s  .  c om
            } finally {
                latch.countDown();
            }
        });
    }

    latch.await();
    executorService.shutdown();
}