Example usage for org.openqa.selenium WebDriver close

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

Introduction

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

Prototype

void close();

Source Link

Document

Close the current window, quitting the browser if it's the last window currently open.

Usage

From source file:com.cloudbees.test.SeleniumTest.java

License:Apache License

private void testSeleniumDriver(WebDriver webDriver) {
    System.err.println("");
    System.err.println("#############################");
    System.err.println("# TEST WITH " + webDriver);
    System.err.println("#############################");
    try {//ww w  .  ja v  a2 s  . c  o  m
        String url = "https://google.com";
        webDriver.get(url);
        Assert.assertEquals("Unexpected page title requesting " + url + " with selenium driver "
                + webDriver.toString() + " displaying " + webDriver.getCurrentUrl(), "Google",
                webDriver.getTitle());
        System.err.println("SUCCESSFULLY invoked Selenium driver" + webDriver.toString() + " with URL "
                + webDriver.getCurrentUrl() + ", page.title='" + webDriver.getTitle() + "'");
    } finally {
        webDriver.close();
        webDriver.quit();
    }
}

From source file:com.comcast.magicwand.drivers.AbstractPhoenixDriver.java

License:Apache License

public void close() {
    WebDriver driver = this.getDriver();

    if (null != driver) {
        driver.close();
    }
}

From source file:com.demo.selenium.example.ChromeExmple.java

License:Apache License

@Test
public void chromeTest() throws InterruptedException {

    System.setProperty("webdriver.chrome.driver", "C:/chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.get("http://www.google.com");
    Thread.sleep(5000);//from   w  ww. j a va  2s .  co  m

    driver.close();
}

From source file:com.demo.selenium.example.GridExampleTest.java

License:Apache License

@Test
public void GridTwoNodeTest() throws MalformedURLException, InterruptedException {

    DesiredCapabilities aDesiredcap = DesiredCapabilities.chrome();
    WebDriver dr = new RemoteWebDriver(new URL("http://172.19.6.46:5555/wd/hub"), aDesiredcap);
    dr.get("http://www.baidu.com");
    dr.manage().window().maximize();//from   w  w w  . j  ava 2 s  . com

    String str[] = new String[] { "java", "selenium", "spring", "mybatis", "jps", "grid", "mysql", "iphone" };
    for (String string : str) {
        WebElement element = dr.findElement(By.xpath(".//*[@id='kw']"));
        element.clear();
        element.sendKeys(string);

        Thread.sleep(1000);

        WebElement buttons = dr.findElement(By.xpath(".//*[@id='su']"));

        System.out.println(buttons.getTagName());

        buttons.click();
    }

    Thread.sleep(2000);

    dr.close();

}

From source file:com.ecofactor.qa.automation.newapp.page.impl.ThermostatPageUIImpl.java

License:Open Source License

/**
 * Checks if is click learn more link redirects new window.
 * @return true, if is click learn more link redirects new window
 * @see com.ecofactor.qa.automation.newapp.page.ThermostatPage#isClickLearnMoreLinkRedirectsNewWindow()
 *///from  ww w. j a  va  2  s  .c o m
@Override
public boolean isClickLearnMoreLinkRedirectsNewWindow() {

    boolean pageRedirected = false;
    final String parentWindowHandle = getDriver().getWindowHandle();
    final WebElement errorModeInfoLink = getElement(getDriver(), By.className(ERROR_MODE_INFO), SHORT_TIMEOUT);
    setLogString("Click on error mode info.", true, CustomLogLevel.LOW);
    errorModeInfoLink.click();
    getAction().rejectAlert();
    // tinyWait();

    final Set<String> windowids = getDriver().getWindowHandles();
    final Iterator<String> iter = windowids.iterator();
    iter.next();
    setLogString("Check if new pop up window opens.", true, CustomLogLevel.LOW);
    setLogString("Switch to other window and verify the title", true, CustomLogLevel.HIGH);
    final WebDriver popup = getDriver().switchTo().window((String) iter.next());

    setLogString("Check URL is :http://ecofactor.uservoice.com/", true, CustomLogLevel.HIGH);
    setLogString("URL is :" + popup.getCurrentUrl(), true, CustomLogLevel.HIGH);

    pageRedirected = popup.getCurrentUrl().contains(mobileConfig.get(MobileConfig.LEARN_MORE_LINK)) ? true
            : false;
    popup.close();
    getDriver().switchTo().window(parentWindowHandle);
    return pageRedirected;
}

From source file:com.emc.kibana.emailer.KibanaEmailer.java

License:Open Source License

private static void generatePdfReports() {

    try {//from  ww  w. ja  v  a2  s  .c o  m
        System.setProperty("webdriver.chrome.driver", chromeDriverPath);

        Map<String, Object> chromeOptions = new HashMap<String, Object>();

        // Specify alternate browser location
        if (chromeBrowserPath != null && !chromeBrowserPath.isEmpty()) {
            chromeOptions.put("binary", chromeBrowserPath);
        }

        DesiredCapabilities capabilities = DesiredCapabilities.chrome();

        capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);

        int index = 1;
        Date timestamp = new Date(System.currentTimeMillis());

        for (Map<String, String> entry : kibanaUrls) {

            String dashboardName = entry.get(NAME_KEY);
            String dashboardUrl = entry.get(URL_KEY);

            if (dashboardUrl == null) {
                continue;
            }

            String filename;

            if ((dashboardName != null)) {
                String invalidCharRemoved = dashboardName.replaceAll("[\\/:\"*?<>|]+", "_").replaceAll(" ",
                        "_");
                filename = invalidCharRemoved + ".png";
            } else {
                filename = "dashboard-" + index++ + ".png";
            }

            WebDriver driver = new ChromeDriver(capabilities);
            driver.manage().window().maximize();
            driver.get(dashboardUrl);

            // let kibana load for x seconds before taking the snapshot
            Integer delay = (screenCaptureDelay != null) ? (screenCaptureDelay * 1000) : (20000);
            Thread.sleep(delay);
            // take screenshot
            File scrnshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

            // generate absolute path filename
            String absoluteFileName = destinationPath + File.separator + DATA_DATE_FORMAT.format(timestamp)
                    + File.separator + filename;
            Map<String, String> fileMap = new HashMap<String, String>();
            // file name portion
            fileMap.put(FILE_NAME_KEY, filename);
            fileMap.put(ABSOLUE_FILE_NAME_KEY, absoluteFileName);

            kibanaScreenCaptures.add(fileMap);
            File destFile = new File(absoluteFileName);

            logger.info("Copying " + scrnshot + " in " + destFile.getAbsolutePath());

            FileUtils.copyFile(scrnshot, destFile);
            driver.close();
        }
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } catch (IOException e1) {
        throw new RuntimeException(e1);
    }
}

From source file:com.evidon.areweprivateyet.Crawler.java

License:Open Source License

private void killPopups(String baseWindow, WebDriver driver) {
    // close any new popups.
    for (String handle : driver.getWindowHandles()) {
        if (!handle.equals(baseWindow)) {
            WebDriver popup = driver.switchTo().window(handle);
            log("\tClosing popup: " + popup.getCurrentUrl());
            popup.close();

            // TODO: need to see if this breaks when there is a modal.
        }/*from w w w .j a  v  a2  s.co m*/
    }

    driver.switchTo().window(baseWindow);
}

From source file:com.gargoylesoftware.htmlunit.WebDriverTestCase.java

License:Apache License

/**
 * Release resources but DON'T close the browser if we are running with a real browser.
 * Note that HtmlUnitDriver is not cached by default, but that can be configured by {@link #isWebClientCached()}.
 *//* w w w  .  j  a v a  2  s. co  m*/
@After
@Override
public void releaseResources() {
    super.releaseResources();

    if (!isWebClientCached()) {
        if (webDriver_ != null) {
            webDriver_.quit();
        }
        assertTrue("There are still JS threads running after the test", getJavaScriptThreads().isEmpty());
    }

    if (useRealBrowser()) {
        synchronized (WEB_DRIVERS_REAL_BROWSERS) {
            final WebDriver driver = WEB_DRIVERS_REAL_BROWSERS.get(getBrowserVersion());
            if (driver != null) {
                try {
                    final String currentWindow = driver.getWindowHandle();

                    final Set<String> handles = driver.getWindowHandles();
                    // close all windows except the current one
                    handles.remove(currentWindow);

                    if (handles.size() > 0) {
                        for (final String handle : handles) {
                            try {
                                driver.switchTo().window(handle);
                                driver.close();
                            } catch (final NoSuchWindowException e) {
                                LOG.error("Error switching to browser window; quit browser.", e);
                                WEB_DRIVERS_REAL_BROWSERS.remove(getBrowserVersion());
                                WEB_DRIVERS_REAL_BROWSERS_USAGE_COUNT.remove(getBrowserVersion());
                                driver.quit();
                                return;
                            }
                        }

                        // we have to force WebDriver to treat the remaining window
                        // as the one we like to work with from now on
                        // looks like a web driver issue to me (version 2.47.2)
                        driver.switchTo().window(currentWindow);
                    }

                    driver.manage().deleteAllCookies();

                    // in the remaining window, load a blank page
                    driver.get("about:blank");
                } catch (final WebDriverException e) {
                    shutDownRealBrowsers();
                }
            }
        }
    }
}

From source file:com.google.appengine.tck.login.UserLogin.java

License:Open Source License

public void login(@Observes EventContext<Before> event) throws Exception {
    Before before = event.getEvent();/*w w w. j a  v a2s .c om*/

    UserIsLoggedIn userIsLoggedIn = null;
    if (before.getTestMethod().isAnnotationPresent(UserIsLoggedIn.class)) {
        userIsLoggedIn = before.getTestMethod().getAnnotation(UserIsLoggedIn.class);
    } else if (before.getTestClass().isAnnotationPresent(UserIsLoggedIn.class)) {
        userIsLoggedIn = before.getTestClass().getAnnotation(UserIsLoggedIn.class);
    }

    if (userIsLoggedIn != null) {
        final URI baseUri = getBaseURI(before.getTestMethod());
        final WebDriver driver = createWebDriver();
        try {
            driver.manage().deleteAllCookies();

            driver.navigate().to(baseUri + USER_LOGIN_SERVLET_PATH + "?location="
                    + URLEncoder.encode(userIsLoggedIn.location(), "UTF-8"));

            // did we navigate to this requested page, or did we get redirected/forwarded to login already
            List<WebElement> loginUrlElts = driver.findElements(By.id("login-url"));
            if (loginUrlElts.size() > 0) {
                String loginURL = loginUrlElts.get(0).getText();

                // check
                if (isInternalLink(loginURL)) {
                    loginURL = baseUri + loginURL;
                }

                // go-to login page
                driver.navigate().to(loginURL);
            }

            // find custom login handler, if exists
            LoginHandler loginHandler = TestBase.instance(getClass(), LoginHandler.class);
            if (loginHandler == null) {
                loginHandler = new DefaultLoginHandler();
            }
            loginHandler.login(driver, new UserLoginContext(userIsLoggedIn));
            // copy cookies
            Set<Cookie> cookies = driver.manage().getCookies();
            for (Cookie cookie : cookies) {
                ModulesApi.addCookie(cookie.getName(), cookie.getValue());
            }
        } finally {
            driver.close();
        }
    }

    event.proceed();
}

From source file:com.hotwire.test.steps.partners.PartnersModelWebApp.java

License:Open Source License

@Override
public void verifyDestinationCitiesPage() {
    ErrorMessenger msg = new ErrorMessenger(getWebdriverInstance());
    msg.getErrorMessagesBlock().get(0).findElement(By.xpath(".//a[contains(@onclick,seeAllCities)]")).click();
    try {/*  ww w .ja va 2 s.  co  m*/
        Thread.sleep(15000);
    } catch (InterruptedException e) {
        /**
         * Wait while all popup windows were loaded...
         * Doesn't work without it.
         */
    }
    String rootWindowHandler = getWebdriverInstance().getWindowHandle();

    /**
     * Get handler of partner's popup windows
     * and wait while inner content was appear
     */

    for (String h : getWebdriverInstance().getWindowHandles()) {
        if (!h.equals(rootWindowHandler) && !h.isEmpty()) {
            WebDriver partnerPopupWebDriver = getWebdriverInstance().switchTo().window(h);

            DestinationsCitiesPage destinationsCitiesPage = new DestinationsCitiesPage(partnerPopupWebDriver);

            destinationsCitiesPage.verifyUrl();
            destinationsCitiesPage.verifyCitesForLetter("A");
            /**
             * If we try to verify params in "for" statement when
             * case will be failed then all other popups
             * will not be closed.
             */
            partnerPopupWebDriver.close();
        }
    }

}