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:org.zaproxy.zap.extension.selenium.ExtensionSelenium.java

License:Apache License

private static WebDriver getWebDriverImpl(Browser browser, String proxyAddress, int proxyPort) {
    DesiredCapabilities capabilities = new DesiredCapabilities();
    if (proxyAddress != null) {
        String httpProxy = proxyAddress + ":" + proxyPort;
        Proxy proxy = new Proxy();
        proxy.setHttpProxy(httpProxy);//  ww w .  j  a  v a2s .c  o  m
        proxy.setSslProxy(httpProxy);
        capabilities.setCapability(CapabilityType.PROXY, proxy);
    }

    switch (browser) {
    case CHROME:
        return new ChromeDriver(capabilities);
    case FIREFOX:
        return new FirefoxDriver(capabilities);
    case HTML_UNIT:
        return new HtmlUnitDriver(capabilities);
    case INTERNET_EXPLORER:
        capabilities.setCapability(InternetExplorerDriver.IE_USE_PRE_PROCESS_PROXY, true);

        return new InternetExplorerDriver(capabilities);
    /* No longer supported in the Selenium standalone jar
     * need to decide if we support older Opera versions 
    case OPERA:
    OperaDriver driver = new OperaDriver(capabilities);
    if (proxyAddress != null) {
        driver.proxy().setProxyLocal(true);
        // XXX Workaround, in operadriver <= 1.5 the HTTPS proxy settings are not set according to desired capabilities
        // For more details see OperaProxy.parse(Proxy)
        driver.proxy().setHttpsProxy(proxyAddress + ":" + proxyPort);
    }
            
    return driver;
    */
    case PHANTOM_JS:
        final ArrayList<String> cliArgs = new ArrayList<>(4);
        cliArgs.add("--ssl-protocol=any");
        cliArgs.add("--ignore-ssl-errors=yes");

        cliArgs.add("--webdriver-logfile=" + Constant.getZapHome() + "/phantomjsdriver.log");
        cliArgs.add("--webdriver-loglevel=WARN");

        capabilities.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, cliArgs);

        return new PhantomJSDriver(capabilities);
    case SAFARI:
        return new SafariDriver(capabilities);
    default:
        throw new IllegalArgumentException("Unknown browser: " + browser);
    }
}

From source file:PokemonGoMapValidator.Config.java

public void configInstance(String driverFile, String profileFile, String mapFile) {
    WebDriver webDriver = null;//from w w w .j  a v a2s .  com

    try {
        System.setProperty("webdriver.chrome.driver", driverFile);

        String currentDirectory = Paths.get(".").toAbsolutePath().normalize().toString();

        ZipFile zipFile = new ZipFile(profileFile);
        zipFile.extractAll(currentDirectory + "/" + "profile" + "/");

        File f = new File(currentDirectory + "/prints/");
        if (!f.isDirectory()) {
            new File(currentDirectory + "/prints/").mkdir();
        }

        HashMap<String, Object> chromePrefs = new HashMap<>();
        chromePrefs.put("profile.default_content_settings.popups", 0);
        chromePrefs.put("download.default_directory", currentDirectory);

        ChromeOptions options = new ChromeOptions();

        //se na user-data-dir nao existir profile do chrome,  gerado um na hora
        options.addArguments("user-data-dir=" + currentDirectory + "/" + "profile");
        options.addArguments("--start-maximized");
        //adicionei esta linha, j que dns e portos andam sempre em mudanas
        options.addArguments("--dns-prefetch-disable");
        //options.addExtensions(new File(extensionFile));
        options.setExperimentalOption("prefs", chromePrefs);

        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
        capabilities.setCapability(ChromeOptions.CAPABILITY, options);
        webDriver = new ChromeDriver(capabilities);

        //pokemongos grow in sextagon shape, so I will force a square resolution
        webDriver.manage().window().setPosition(new Point(XCOORD, YCOORD));
        if (MAPDIMENSION > 0) {
            webDriver.manage().window().setSize(new Dimension(MAPDIMENSION, MAPDIMENSION));
        } else {
            webDriver.manage().window().maximize();
        }

        //in the code below, I tried to create a square, but the width's and height's
        //seem to change, and I didn't figured out why and how
        //TODO in the future
        /*
        webDriver.get("http://www.google.com");
        Thread.sleep(1000);
        Dimension win_size = webDriver.manage().window().getSize();
                
        WebElement html = webDriver.findElement(By.tagName("html"));
        int inner_width = Integer.parseInt(html.getAttribute("clientWidth"));
        int outer_width = win_size.width - inner_width;
        int inner_height = Integer.parseInt(html.getAttribute("clientHeight"));
        int outer_height = win_size.height - inner_height;
                
        //pokemongos grow in sextagon shape, so I will force a square resolution
        webDriver.manage().window().setPosition(new Point(0, -1080));
        webDriver.manage().window().setSize(new Dimension(800 + outer_width, 600 + outer_height));
                
        if (VALIDATEBROWSER) {
        new Graphics().browserDimension(webDriver);
        }
                
        */

        RunComparison comparison = new RunComparison();
        comparison.comparison(currentDirectory, webDriver, mapFile);

    } catch (ZipException | IOException | InterruptedException ex) {
        System.err.println("Config error: " + ex.getMessage());
    } finally {
        try {
            if (webDriver != null) {
                Exit sair = new Exit();
                sair.exit(webDriver);
                System.out.println("ChromeDriver and Chrome unloaded");
            }
        } catch (InterruptedException ex) {
            System.err.println("Exit error: " + ex.getMessage());
        }
    }
}

From source file:renascere.Renascere.java

License:Open Source License

/**
 * @Description Method that opens a specified browser
 *///from   www. ja  va 2  s  .c o  m
static WebDriver openABrowser(browser bBrowserName) {
    WebDriver driver = null;
    String sDriverName = null;
    DesiredCapabilities DesireCaps = new DesiredCapabilities();

    try {
        //Creating browser instance
        switch (bBrowserName) {
        case FIREFOX:
            //Initializing Driver
            FirefoxProfile browserProfile = new FirefoxProfile();

            //Adding following preferences to download files
            browserProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream");
            browserProfile.setPreference("browser.download.folderList", 2);
            browserProfile.setPreference("browser.download.dir", Vars.os_PathOut);
            browserProfile.setPreference("browser.download.manager.alertOnEXEOpen", false);
            browserProfile.setPreference("browser.helperApps.neverAsk.saveToDisk",
                    "application/msword, application/csv, "
                            + "application/ris, text/csv, image/png, application/pdf, text/html, "
                            + "text/plain, application/zip, application/x-zip, application/x-zip-compressed, "
                            + "application/download, application/octet-stream");
            browserProfile.setPreference("browser.download.manager.showWhenStarting", false);
            browserProfile.setPreference("browser.download.manager.focusWhenStarting", false);
            browserProfile.setPreference("browser.download.useDownloadDir", true);
            browserProfile.setPreference("browser.helperApps.alwaysAsk.force", false);
            browserProfile.setPreference("browser.download.manager.alertOnEXEOpen", false);
            browserProfile.setPreference("browser.download.manager.closeWhenDone", true);
            browserProfile.setPreference("browser.download.manager.showAlertOnComplete", false);
            browserProfile.setPreference("browser.download.manager.useWindow", false);
            browserProfile.setPreference("services.sync.prefs.sync.browser.download.manager.showWhenStarting",
                    false);
            browserProfile.setPreference("pdfjs.disabled", true);
            browserProfile.setPreference("browser.download.manager.openDelay", 100000);
            browserProfile.setPreference("browser.download.animateNotifications", false);
            driver = new FirefoxDriver(browserProfile);
            break;
        case CHROME:
            //Determine driver to be used
            sDriverName = Vars.os_Name.toLowerCase().contains("win") ? "chromedriver-win.exe"
                    : (Vars.os_Name.toLowerCase().contains("mac") ? "chromedriver-mac" : "chromedriver-lnx");

            //Initializing Driver
            System.setProperty("webdriver.chrome.driver", Vars.os_PathRef + sDriverName);
            DesireCaps = DesiredCapabilities.chrome();
            driver = new ChromeDriver(DesireCaps);
            break;
        case IE:
            //Determine driver to be used
            System.setProperty("webdriver.ie.driver", Vars.os_PathRef + "IEDriverServer-win.exe");
            DesireCaps = Vars.os_Name.toLowerCase().contains("win") ? DesiredCapabilities.internetExplorer()
                    : null;
            if (DesireCaps == null) {
                throw new Exception("Invalid OS for browser.");
            }

            //Create instance
            driver = new InternetExplorerDriver(DesireCaps);
            break;
        case OPERA:
            //Determine driver to be used
            sDriverName = Vars.os_Name.toLowerCase().contains("win") ? "operadriver-win.exe"
                    : (Vars.os_Name.toLowerCase().contains("mac") ? "operadriver-mac" : "operadriver-lnx");

            //Initializing Driver
            System.setProperty("webdriver.chrome.driver", Vars.os_PathRef + sDriverName);
            driver = new ChromeDriver();
            break;
        case SAFARI:
            //Initializing Driver
            driver = new SafariDriver();
            break;
        case PHANTOMJS:
            //Determine driver to be used
            sDriverName = Vars.os_Name.toLowerCase().contains("win") ? "phantomjs-win.exe"
                    : (Vars.os_Name.toLowerCase().contains("mac") ? "phantomjs-mac" : "phantomjs-lnx");

            //Initializing Driver
            DesireCaps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
                    Vars.os_PathRef + sDriverName);
            driver = new PhantomJSDriver();
            break;
        default:
            throw new Exception("Unsupported browser.");
        }

        //Getting additional browser information
        Vars.ts_BHandler = driver.getWindowHandle();

    } catch (Exception e) {
        frmError("creating a browser instance (" + bBrowserName + ")", e.getMessage(), severity.HIGH);
    }
    return driver;
}

From source file:Search.DriverSetup.java

public static void GetDriver(int browserId) {
    {//  w  ww  . j  ava 2 s .  c  o  m
        switch (browserId) {
        case 1:
            // For Firefox Driver
            driver = new FirefoxDriver();
            break;

        case 2:
            // For Chrome Driver
            File file = new File("src/main/resources/chromedriver.exe");
            String absolutePath = file.getAbsolutePath();
            ChromeOptions options = new ChromeOptions();
            options.addArguments("chrome.switches", "--disable-extensions");
            System.setProperty("webdriver.chrome.driver", absolutePath);

            // System.setProperty("webdriver.chrome.driver",
            //       "D:\\NetBeansProjects\\Max-IDS4.0\\src\\main\\resources\\chromedriver.exe");

            driver = new ChromeDriver(options);
            break;

        case 3:
            // For IE Driver
            File file1 = new File("src/main/resources/IEDriverServer.exe");
            String absolutePath1 = file1.getAbsolutePath();
            System.setProperty("webdriver.ie.driver", absolutePath1);
            driver = new InternetExplorerDriver();
        }
    }
}

From source file:snapshot.webdriver.WebDriverHelper.java

License:Open Source License

/**
 * Gets a Local WebDriver/*from www . j  a v a2 s. co  m*/
 *
 * @param driverName
 * @param version
 * @return
 * @throws MalformedURLException
 */
public static WebDriver getDriver(String driverName, String version) throws MalformedURLException {
    WebDriver driver = null;
    DesiredCapabilities capabilities = getCapabilities(driverName, version, false);
    if (driverName.equalsIgnoreCase("firefox")) {
        driver = new FirefoxDriver(capabilities);
    } else if (driverName.equalsIgnoreCase("chrome")) {
        driver = new ChromeDriver(capabilities);
    } else if (driverName.equalsIgnoreCase("ie") || driverName.equalsIgnoreCase("internet explorer")) {
        driver = new InternetExplorerDriver(capabilities);
    } else if (driverName.equalsIgnoreCase("phantomjs")) {
        driver = new PhantomJSDriver(capabilities);
    }
    return driver;
}

From source file:streaming.crawler.WebDriverResource.java

License:Apache License

private WebDriver doCreateWebDriver(boolean headless, String browserType,
        Class<? extends WebDriver> defaultWebDriverClass, Long pageLoadTimeout, Long scriptTimeout,
        Long implicitlyWait//ww  w .j a va 2 s .  c  o m

) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {

    DesiredCapabilities capabilities = new DesiredCapabilities(DEFAULT_CAPABILITIES);
    ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.merge(DEFAULT_CHROME_CAPABILITIES);
    // Use headless mode by default, GUI mode can be used for debugging
    chromeOptions.setHeadless(headless);
    if (headless) {
        // Do not downloading images in headless mode
        chromeOptions.addArguments("--blink-settings=imagesEnabled=false");
    }

    // Reset proxy
    capabilities.setCapability(CapabilityType.PROXY, (Object) null);
    chromeOptions.setCapability(CapabilityType.PROXY, (Object) null);

    // Choose the WebDriver
    WebDriver driver;
    if (browserType == BrowserType.CHROME) {
        driver = new ChromeDriver(chromeOptions);
    } else {
        if (RemoteWebDriver.class.isAssignableFrom(defaultWebDriverClass)) {
            driver = defaultWebDriverClass.getConstructor(Capabilities.class).newInstance(capabilities);
        } else {
            driver = defaultWebDriverClass.getConstructor().newInstance();
        }
    }

    // Set timeouts
    WebDriver.Timeouts timeouts = driver.manage().timeouts();
    timeouts.pageLoadTimeout(pageLoadTimeout, TimeUnit.SECONDS);
    timeouts.setScriptTimeout(scriptTimeout, TimeUnit.SECONDS);
    timeouts.implicitlyWait(implicitlyWait, TimeUnit.SECONDS);

    // Set log level
    if (driver instanceof RemoteWebDriver) {
        RemoteWebDriver remoteWebDriver = (RemoteWebDriver) driver;

        final Logger webDriverLog = LoggerFactory.getLogger(WebDriver.class);
        Level level = Level.FINE;
        if (webDriverLog.isDebugEnabled()) {
            level = Level.FINER;
        } else if (webDriverLog.isTraceEnabled()) {
            level = Level.ALL;
        }

        remoteWebDriver.setLogLevel(level);
    }

    return driver;
}

From source file:test.chrome.ChromeTest.java

License:Open Source License

public static void chrome(String baseurl, boolean useKeycloak) {

    WebDriver driver = null;/*from ww  w  . j  a va  2s .c o  m*/
    try {
        DesiredCapabilities desiredCapabilities = DesiredCapabilities.chrome();
        desiredCapabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
        desiredCapabilities.setCapability(CapabilityType.SUPPORTS_APPLICATION_CACHE, false);

        ChromeDriverManager.getInstance().setup();
        driver = new ChromeDriver(desiredCapabilities);
        driver.manage().window().setSize(new Dimension(Utils.WINDOW_WIDTH, Utils.WINDOW_HEIGHT));
        driver.manage().timeouts().implicitlyWait(Utils.DEFAULT_WAITING_TIME, TimeUnit.SECONDS);

        TestScenario.useKeycloak = useKeycloak;
        TestScenario.test(driver, baseurl);
    } finally {
        if (driver != null) {
            driver.quit();
        }
    }
}

From source file:test.seleniumbugmvn.Main.java

public static void main(String[] args) {

    DesiredCapabilities defaults = DesiredCapabilities.chrome();

    LoggingPreferences prefs = new LoggingPreferences();
    prefs.enable(LogType.BROWSER, Level.ALL);
    prefs.enable(LogType.CLIENT, Level.ALL);
    prefs.enable(LogType.DRIVER, Level.ALL);
    defaults.setCapability(CapabilityType.LOGGING_PREFS, prefs);
    browser = new ChromeDriver(defaults);

    browser.get("http://ladariha.cz/tmp/chromedriver/index.html");
    waitFor(7000);/*w ww .  jav a  2 s .c  o  m*/
    new Actions(browser).clickAndHold(browser.findElement(By.xpath("//*[@id='source']"))).moveByOffset(1, 1)
            .moveToElement(browser.findElement(By.xpath("//*[@id='target']"))).moveByOffset(1, 1).release()
            .perform();

    //        new Actions(browser).dragAndDrop(browser.findElement(By.xpath("//*[@id='source']")), browser.findElement(By.xpath("//*[@id='target']")));
    browser.quit();
    System.out.println("done");
}

From source file:Utility.General.java

License:Open Source License

public static WebDriver GetBrowser(String driverName) {

    WebDriver driver = null;//  www .j  a va 2  s  . c  o  m

    switch (driverName) {
    case "IE":
        System.setProperty("webdriver.ie.driver", new General().LoadProperties().getProperty("ieDriver"));
        driver = new InternetExplorerDriver();
        break;
    case "Firefox":
        driver = new FirefoxDriver();
        break;
    case "Chrome":
        System.setProperty("webdriver.chrome.driver",
                new General().LoadProperties().getProperty("chromeDriver"));
        ChromeOptions options = new ChromeOptions();
        options.addArguments("test-type");
        driver = new ChromeDriver(options);
        break;
    case "Safari":
        driver = new SafariDriver();
        break;
    }
    Log.info("Connnection opened using " + driverName + " browser.");

    return driver;
}