Example usage for org.openqa.selenium WebDriver manage

List of usage examples for org.openqa.selenium WebDriver manage

Introduction

In this page you can find the example usage for org.openqa.selenium WebDriver manage.

Prototype

Options manage();

Source Link

Document

Gets the Option interface

Usage

From source file:com.liferay.faces.test.selenium.browser.internal.BrowserDriverFactoryImpl.java

License:Open Source License

@Override
public BrowserDriver getBrowserDriverImplementation(String browserName, boolean browserHeadless,
        boolean browserSimulateMobile) {

    WebDriver webDriver;

    if ("chrome".equals(browserName)) {

        ChromeOptions chromeOptions = new ChromeOptions();
        String chromeBinaryPath = TestUtil.getSystemPropertyOrDefault("webdriver.chrome.bin", null);

        if (chromeBinaryPath != null) {

            chromeOptions.setBinary(chromeBinaryPath);
            logger.info("Chrome Binary: {}", chromeBinaryPath);
        }/*from w w w . j av a  2s.c  o  m*/

        if (browserHeadless) {

            // The start-maximized argument does not work correctly in headless mode, so set the window size to
            // 1920x1200 (resolution of a 15.4 inch screen).
            chromeOptions.addArguments("headless", "disable-gpu", "window-size=1920,1200");
        } else {
            chromeOptions.addArguments("start-maximized");
        }

        if (browserSimulateMobile) {
            chromeOptions.addArguments("user-agent=\"" + IPHONE_7_IOS_10_0_USER_AGENT + "\"");
        }

        webDriver = new ChromeDriver(chromeOptions);
    } else if ("firefox".equals(browserName)) {

        // The value of this property is obtained automatically by FirefoxDriver.
        String firefoxBinaryPath = TestUtil.getSystemPropertyOrDefault("webdriver.firefox.bin", null);

        if (firefoxBinaryPath != null) {
            logger.info("Firefox Binary: {}", firefoxBinaryPath);
        }

        FirefoxProfile firefoxProfile = new FirefoxProfile();

        if (browserHeadless) {
            throw new UnsupportedOperationException("Headless mode is not yet supported for Firefox");
        }

        if (browserSimulateMobile) {
            firefoxProfile.setPreference("general.useragent.override", IPHONE_7_IOS_10_0_USER_AGENT);
        }

        webDriver = new FirefoxDriver(firefoxProfile);
    } else if ("phantomjs".equals(browserName)) {

        // The value of this property is obtained automatically by PhantomJSDriver.
        String phantomJSBinaryPath = TestUtil.getSystemPropertyOrDefault("phantomjs.binary.path", null);

        if (phantomJSBinaryPath != null) {
            logger.info("PhantomJS Binary: {}", phantomJSBinaryPath);
        }

        DesiredCapabilities desiredCapabilities = new DesiredCapabilities();

        if (!browserHeadless) {
            throw new UnsupportedOperationException("Non-headless mode is not yet supported for PhantomJS");
        }

        if (browserSimulateMobile) {

            desiredCapabilities.setCapability(
                    PhantomJSDriverService.PHANTOMJS_PAGE_SETTINGS_PREFIX + "userAgent",
                    IPHONE_7_IOS_10_0_USER_AGENT);
            desiredCapabilities.setCapability(
                    PhantomJSDriverService.PHANTOMJS_PAGE_CUSTOMHEADERS_PREFIX + "User-Agent",
                    IPHONE_7_IOS_10_0_USER_AGENT);
        }

        // Set the Accept-Language header to "en-US,en;q=0.8" to ensure that it isn't set to "en-US," (the default).
        desiredCapabilities.setCapability(
                PhantomJSDriverService.PHANTOMJS_PAGE_CUSTOMHEADERS_PREFIX + "Accept-Language",
                "en-US,en;q=0.8");

        String phantomJSLogLevel;

        if (logger.isDebugEnabled()) {
            phantomJSLogLevel = "DEBUG";
        } else if (logger.isInfoEnabled()) {
            phantomJSLogLevel = "INFO";
        } else if (logger.isWarnEnabled()) {
            phantomJSLogLevel = "WARN";
        } else if (logger.isErrorEnabled()) {
            phantomJSLogLevel = "ERROR";
        } else {
            phantomJSLogLevel = "NONE";
        }

        String[] phantomArgs = new String[1];
        phantomArgs[0] = "--webdriver-loglevel=" + phantomJSLogLevel;
        desiredCapabilities.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, phantomArgs);
        webDriver = new PhantomJSDriver(desiredCapabilities);
    } else if ("htmlunit".equals(browserName)) {

        if (!browserHeadless) {
            throw new UnsupportedOperationException("Non-headless mode is not yet supported for HtmlUnit");
        }

        if (browserSimulateMobile) {
            webDriver = new HtmlUnitDriverLiferayFacesImpl(IPHONE_7_IOS_10_0_USER_AGENT);
        } else {
            webDriver = new HtmlUnitDriverLiferayFacesImpl();
        }
    } else if ("jbrowser".equals(browserName)) {

        if (!browserHeadless) {
            throw new UnsupportedOperationException("Non-headless mode is not yet supported for JBrowser");
        }

        if (browserSimulateMobile) {
            throw new UnsupportedOperationException("Mobile simulation is not yet supported for JBrowser.");
        }

        webDriver = new JBrowserDriver();
    } else {
        throw new UnsupportedOperationException("Browser with not supported: " + browserName);
    }

    if (!"chrome".equals(browserName)) {
        webDriver.manage().window().maximize();
    }

    return getBrowserDriverImplementation(webDriver, browserHeadless, browserSimulateMobile);
}

From source file:com.liferay.faces.test.selenium.browser.internal.BrowserDriverImpl.java

License:Open Source License

@Override
public void clearBrowserCookies() {

    WebDriver webDriver = getWebDriver();
    webDriver.manage().deleteAllCookies();
}

From source file:com.liferay.faces.test.selenium.browser.internal.BrowserDriverImpl.java

License:Open Source License

@Override
public Set<Cookie> getBrowserCookies() {

    WebDriver webDriver = getWebDriver();

    return webDriver.manage().getCookies();
}

From source file:com.liferay.faces.test.selenium.browser.internal.BrowserDriverImpl.java

License:Open Source License

@Override
public void setPageLoadTimeout(int waitTimeOutInSeconds) {

    WebDriver webDriver = getWebDriver();
    webDriver.manage().timeouts().pageLoadTimeout(waitTimeOutInSeconds, TimeUnit.SECONDS);
}

From source file:com.maoyan.pf.webcollector.spider.ShowrateCrawler.java

License:Open Source License

public static void main(String[] args) throws Exception {
    Executor executor = new Executor() {
        @Override//from  www.ja v a  2 s  .co  m
        public void execute(CrawlDatum datum, CrawlDatums next) throws Exception {
            MongoClient mongoClient = new MongoClient("localhost", 27017);
            // ?
            // DBCollection dbCollection = mongoClient.getDB("maoyan_crawler").getCollection("rankings_am"); 
            DB db = mongoClient.getDB("maoyan_crawler");
            // ?????
            Set<String> colls = db.getCollectionNames();
            for (String s : colls) {
                // Collection(?"")
                if (s.equals("show_rate")) {
                    db.getCollection(s).drop();
                }
            }
            DBCollection dbCollection = db.getCollection("show_rate");
            //                ProfilesIni pi = new ProfilesIni();
            //                FirefoxProfile profile = pi.getProfile("default");
            WebDriver driver = new FirefoxDriver();
            driver.manage().window().maximize();
            driver.manage().timeouts().pageLoadTimeout(3, TimeUnit.SECONDS);
            //                driver.setJavascriptEnabled(false);
            System.out.println("??\n");
            driver.get(datum.getUrl());
            //                System.out.println(driver.getPageSource());
            List<WebElement> movie_name = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c1 lineDot']"));
            List<WebElement> boxoffice_rate = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c2 red']"));
            List<WebElement> visit_pershow = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c3 gray']"));
            WebElement title = driver.findElement(By.xpath("//p[@id='pieTip']"));
            for (int i = 0; i < movie_name.size(); i++) {
                String movie_name_val = movie_name.get(i).getText();
                String boxofficerate_val = boxoffice_rate.get(i).getText();
                String visit_pershow_val = visit_pershow.get(i).getText();
                BasicDBObject dbObject = new BasicDBObject();
                dbObject.append("title", title.getText()).append("is_gold", "?")
                        .append("show_type", "?").append("movie_name", movie_name_val)
                        .append("boxoffice_rate", boxofficerate_val).append("visit_pershow", visit_pershow_val);
                dbCollection.insert(dbObject);
            }
            System.out.println("?\n");
            WebElement click_gold = driver.findElement(By.id("playPlan_time"));
            click_gold.click();
            String gold_seat = driver.getWindowHandle();
            driver.switchTo().window(gold_seat);
            List<WebElement> movie_name_gold = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c1 lineDot']"));
            List<WebElement> boxoffice_rate_gold = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c2 red']"));
            List<WebElement> visit_pershow_gold = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c3 gray']"));
            WebElement title_gold = driver.findElement(By.xpath("//p[@id='pieTip']"));
            for (int i = 0; i < movie_name_gold.size(); i++) {
                String movie_name_val = movie_name_gold.get(i).getText();
                String boxofficerate_val = boxoffice_rate_gold.get(i).getText();
                String visit_pershow_val = visit_pershow_gold.get(i).getText();
                BasicDBObject dbObject = new BasicDBObject();
                dbObject.append("title", title_gold.getText()).append("is_gold", "")
                        .append("show_type", "?").append("movie_name", movie_name_val)
                        .append("boxoffice_rate", boxofficerate_val).append("visit_pershow", visit_pershow_val);
                dbCollection.insert(dbObject);
            }
            System.out.println("?\n");
            WebElement click_vist = driver.findElement(By.xpath("//*[@id='show--type']"));
            click_vist.click();
            String gold_vist = driver.getWindowHandle();
            driver.switchTo().window(gold_vist);
            List<WebElement> movie_name_gold_visit = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c1 lineDot']"));
            List<WebElement> boxoffice_rate_gold_visit = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c2 red']"));
            List<WebElement> visit_pershow_gold_visit = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c3 gray']"));
            WebElement title_gold_visit = driver.findElement(By.xpath("//p[@id='pieTip']"));
            for (int i = 0; i < movie_name_gold_visit.size(); i++) {
                String movie_name_val = movie_name_gold_visit.get(i).getText();
                String boxofficerate_val = boxoffice_rate_gold_visit.get(i).getText();
                String visit_pershow_val = visit_pershow_gold_visit.get(i).getText();
                BasicDBObject dbObject = new BasicDBObject();
                dbObject.append("title", title_gold_visit.getText()).append("is_gold", "")
                        .append("show_type", "").append("movie_name", movie_name_val)
                        .append("boxoffice_rate", boxofficerate_val).append("visit_pershow", visit_pershow_val);
                dbCollection.insert(dbObject);
            }
            System.out.println("?\n");
            click_gold.click();
            String normal_seat = driver.getWindowHandle();
            driver.switchTo().window(normal_seat);
            List<WebElement> movie_name_normal_seat = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c1 lineDot']"));
            List<WebElement> boxoffice_rate_normal_seat = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c2 red']"));
            List<WebElement> visit_pershow_normal_seat = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c3 gray']"));
            WebElement title_normal_seat = driver.findElement(By.xpath("//p[@id='pieTip']"));
            for (int i = 0; i < movie_name_normal_seat.size(); i++) {
                String movie_name_val = movie_name_normal_seat.get(i).getText();
                String boxofficerate_val = boxoffice_rate_normal_seat.get(i).getText();
                String visit_pershow_val = visit_pershow_normal_seat.get(i).getText();
                BasicDBObject dbObject = new BasicDBObject();
                dbObject.append("title", title_normal_seat.getText()).append("is_gold", "?")
                        .append("show_type", "").append("movie_name", movie_name_val)
                        .append("boxoffice_rate", boxofficerate_val).append("visit_pershow", visit_pershow_val);
                dbCollection.insert(dbObject);
            }

            driver.close();
            driver.quit();
            mongoClient.close();
        }
    };

    //DBDBManager
    DBManager manager = new BerkeleyDBManager("maoyan");
    //Crawler?DBManagerExecutor
    Crawler crawler = new Crawler(manager, executor);
    crawler.addSeed("http://pf.maoyan.com/show/rate");
    crawler.start(1);
}

From source file:com.mgmtp.jfunk.web.BaseWebDriverProvider.java

License:Apache License

@Override
public WebDriver get() {
    String webDriverKey = config.get(WebConstants.WEBDRIVER_KEY);
    log.info("Creating new WebDriver instance with key '{}'...", webDriverKey);

    DesiredCapabilities capabilities = capabilitiesMap.get(webDriverKey);

    // we must disable WebDriver's overlapping check to be able to use our own topMostElementCheck flag
    capabilities.setCapability("overlappingCheckDisabled", true);

    //TODO this flag tells FirefoxDriver whether to run in legacy mode or in Marionette mode
    // => remove it, once the W3C actions API is correctly implemented in GeckoDriver
    Boolean isWebdriverFirefoxMarionette = config
            .getBoolean(FirefoxDriver.SystemProperty.DRIVER_USE_MARIONETTE);
    capabilities.setCapability(FirefoxDriver.MARIONETTE, isWebdriverFirefoxMarionette);

    // post event so users can customize capabilities
    eventBus.post(new BeforeWebDriverCreationEvent(webDriverKey, capabilities));

    WebDriver webDriver = createWebDriver(capabilities);
    checkState(!(webDriver instanceof EventFiringWebDriver),
            "WebDrivers must not be wrapped explicitly into an EventFiringWebDriver. This is implicitly done by jFunk.");

    long implicitWaitSeconds = config.getLong(WebConstants.WEBDRIVER_IMPLICIT_WAIT_SECONDS, 0L);
    if (implicitWaitSeconds > 0) {
        webDriver.manage().timeouts().implicitlyWait(implicitWaitSeconds, TimeUnit.SECONDS);
    }/*from w ww  . j  a  v  a  2s  .  c  o m*/

    EventFiringWebDriver eventFiringWebDriver = new EventFiringWebDriver(webDriver);
    for (WebDriverEventListener listener : eventListeners) {
        eventFiringWebDriver.register(listener);
    }
    return eventFiringWebDriver;
}

From source file:com.molo.dagger.LogTools.java

License:Apache License

public static String screenShot(BrowserEmulator be) {
    String dir = "screenshot"; // TODO
    String time = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date());
    String screenShotPath = dir + File.separator + time + ".png";

    WebDriver augmentedDriver = null;
    if (GlobalSettings.browserCoreType == 1 || GlobalSettings.browserCoreType == 3) {
        augmentedDriver = be.getBrowserCore();
        augmentedDriver.manage().window().setPosition(new Point(0, 0));
        augmentedDriver.manage().window().setSize(new Dimension(9999, 9999));
    } else if (GlobalSettings.browserCoreType == 2) {
        augmentedDriver = new Augmenter().augment(be.getBrowserCore());
    } else {//w ww. ja  v a 2 s  .  c om
        return "Incorrect browser type";
    }

    try {
        File sourceFile = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(sourceFile, new File(screenShotPath));
    } catch (Exception e) {
        e.printStackTrace();
        return "Failed to screenshot";
    }

    // Convert '\' into '/' for web image browsing.
    return screenShotPath.replace("\\", "/");
}

From source file:com.mx.santander.lh.obpyme.Operacion.OperacionesMarketingSantander.java

public void OperacionesCampaniaMArketing(WebDriver driver) throws InterruptedException, IOException {

    //OPERACIONES DE MANEJO DE BROWSER
    driver.manage().window().maximize();
    driver.get("http://www.google.com");

    //VALIDACION DE ELEMENTOS PARA INICIO DE PRUEBA
    Thread.sleep(3000);/*w  w  w.  jav a2 s . c o m*/
    if (validacionesMArketing.ValidaElementosMarketingSantander(driver)) {
        System.out.println("----- INICIA TEST AUTOMATIZADO -----");
        System.out.println("------------------------------------");
        System.out.println("Caso de prueba: " + datos.RecuperarDatosExcel().getCasoPrueba());
        System.out.println("");
        //REALIZA LA BUSQUEDA DE LA EMPRESA A LA QUE SE LE VA A REALIZAR EL MARKETING
        elementos.ElementoTextInputBusqueda(driver).sendKeys(datos.RecuperarDatosExcel().getEmpresaMarketing());
        elementos.ElementoTextInputBusqueda(driver).sendKeys(Keys.ENTER);
        Thread.sleep(3000);

        System.out.println("----- DATOS DE PRUEBA -----");
        System.out.println("---------------------------");
        System.out.println("EMPRESA: " + datos.RecuperarDatosExcel().getEmpresaMarketing());
        System.out.println("ENLACE TOP 1: " + datos.RecuperarDatosExcel().getPosicionamientoMarketingTopURL());
        System.out.println("TOP NUMBER: " + datos.RecuperarDatosExcel().getTopNumber());
        System.out.println("");

        //VALIDA SI SE ENCONTRARON VALORES EN LA BUSQUEDA.
        if (validacionesMArketing.ValidaListaElementosResultados(driver)) {
            List<WebElement> listaElementos = elementos.ListaURLBusqueda(driver);
            //RECORREMOS LA LISTA DE ELEMENTOS RECUPERADOS PARA IDENTIFICAR SI LA EMPRESA DE MARKETING SE ENCUENTRA EN LA POSICION INDICADA
            System.out.println("----- RESULTADO DEL TEST AUTOMATIZADO -----");
            System.out.println("-------------------------------------------");

            int contador = 0;
            for (WebElement elemento : listaElementos) {
                contador++;
                //LA EMPRESA SE ENCUENTRA EN EL TOP TEN
                if (elemento.getText().equals(datos.RecuperarDatosExcel().getPosicionamientoMarketingTopURL())
                        && contador == datos.RecuperarDatosExcel().getTopNumber()) {
                    System.out.println("LA EMPRESA SE ENCUENTRA EN EL TOP TEN DE BUSQUEDA EN GOOGLE");
                    driver.close();
                    break;
                }
                //LA EMPRESA NO SE ENCUENTRA EN EL TOP TEN.
                if (contador == listaElementos.size()) {
                    System.out
                            .println("LA EMPRESA NO SE ENCUENTRA EN EL TOP TEN INICIAR CAMPAA DE MARKETING");
                    driver.close();
                }
            }
        }
    } else {
        //NO SE ENCONTRARON LOS ELEMENTOS NECESARIOS PARA COMENZAR CON LA PRUEBA
        System.out.println("LA BUSQUEDA EN GOOGLE NO SE ENCUENTRA DISPONIBLE POR EL MOMENTO");
    }

}

From source file:com.mycompany.browserManipulationUtilities.BrowserResizerUtility.java

/**
 * Resizes the browser controlled by the WebDriver driver so that external frame (not the view port) fits the inputed dimensions
 * sourced from http://stackoverflow.com/questions/16664433/how-to-resize-current-browser-window-in-selenium-webdriver-with-java
 * @param browser/* w  ww . ja va  2  s  .c o m*/
 * @param xDim
 * @param yDim 
 */
public static void resizeExternalBrowserWindow(WebDriver browser, int xDim, int yDim) {
    Dimension dimension = new Dimension(xDim, yDim);
    browser.manage().window().setSize(dimension);
}

From source file:com.mycompany.firstmavenproject.DriverFactory.java

public static WebDriver create(String type) {
    WebDriver driver = null;

    if (type.contains("FirefoxDriver")) {
        driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    } else if (type.contains("ChromeDriver")) {
        driver = new ChromeDriver();
    } else if (type.contains("InternetExplorerDriver")) {
        driver = new InternetExplorerDriver();
    } else if (type.contains("OperaDriver")) {
        driver = new OperaDriver();
    } else if (type.contains("SafariDriver")) {
        driver = new SafariDriver();
    }/*  w w w. j av  a  2s.  c om*/
    return driver;
}