Example usage for org.openqa.selenium WebDriver quit

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

Introduction

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

Prototype

void quit();

Source Link

Document

Quits this driver, closing every associated window.

Usage

From source file:calc.CalculatorUIT.java

public void testCodesCrud(DesiredCapabilities browser) throws Exception {

    ExtentReports logger = new ExtentReports("target//advancedReport.html", false);
    ExtentTest test1 = logger.startTest("Verify Target String");
    ExtentTest test2 = logger.startTest("Verify Calculation Result");

    WebDriver driver = null;
    System.out.println("Attempt connect to Selenium Node @ " + NodeURL);
    File pathToBinary = new File("/opt/firefox46/firefox/firefox-bin");
    FirefoxBinary ffBinary = new FirefoxBinary(pathToBinary);
    FirefoxProfile firefoxProfile = new FirefoxProfile();
    driver = new FirefoxDriver(ffBinary, firefoxProfile);
    try {//from ww w  .ja  va2  s.  c o m
        System.out.println("attempt connect to target: " + TargetURL);
        driver.get(TargetURL);
        //input a addition 12+8 example in the calculator web-application;
        driver.findElement(By.xpath("(//input[@id='buttonRow'])[2]")).click();
        driver.findElement(By.xpath("(//input[@id='buttonRow'])[3]")).click();
        driver.findElement(By.xpath("(//input[@id='buttonRow'])[12]")).click();
        driver.findElement(By.xpath("(//input[@id='buttonRow'])[10]")).click();
        driver.findElement(By.xpath("(//input[@id='buttonRow'])[15]")).click();

        //search target string value
        String targetStr = "Welcome to the Demo";

        //verify result
        boolean isFound = (driver.findElement(By.tagName("body")).getText()).contains(targetStr);
        boolean result = driver.findElement(By.name("display")).getAttribute("value").contains("84");

        //verify title  
        if (isFound == true) {
            test1.log(LogStatus.PASS, "Title has been verified");
        }
        if (isFound == false) {
            test1.log(LogStatus.FAIL, "Title has NOT been verified");
        }

        //verify result     
        if (result == true) {
            test2.log(LogStatus.PASS,
                    "The Calculation result was correct: [12 multiply by 7 gave output of 84]");
        } else {
            test2.log(LogStatus.FAIL,
                    "The Calculation result was not correct [the title is[Welcome to the Demo!]");

        }
        logger.endTest(test1);
        logger.endTest(test2);
        logger.flush();

        System.out.println("look for= [" + targetStr + "]");
        System.out.println("did we find it? [" + isFound + "]");

        System.out.println("calculate 12 multiply by 7");
        System.out.println("Was the result 84 ? [" + result + "]");

        Assert.assertTrue(isFound);
        Assert.assertTrue(result);
        //  Assert.assertEquals("hell",driver.getTitle());
        //doTest(driver); 
        // rest of test commands come here
    } catch (Exception e) {
        e.printStackTrace();
        Assert.assertTrue(e.getMessage(), false);
    } finally {
        if (driver != null) {
            driver.quit();
        }
    }
}

From source file:ch.vorburger.vaadin.designer.tests.web.VaadinServerTest.java

License:Apache License

@Test
@Ignore // TODO reactivate when http://dev.vaadin.com/ticket/9386 is fixed?
public void testStartVaadinServer() throws Exception {
    VaadinServer server = new VaadinServer() {
        @Override//ww  w .  j av  a2  s .c  o  m
        protected Class<? extends Application> getVaadinApplicationClass() {
            return VaadinTestApplication.class;
        }
    };

    try {
        server.start();
        // Check if "Saluton!" button shows up:
        WebDriver driver = new InternetExplorerDriver();
        driver.get(server.getURL());
        WebElement button = driver.findElement(By.id(HTML_ID));
        String text = button.getText();
        Assert.assertEquals("Saluton!", text);
        driver.quit();

    } finally {
        server.stop();
    }
}

From source file:cn.edu.hfut.dmic.webcollector.example.FirefoxSelenium3.java

License:Open Source License

public static void main(String[] args) throws Exception {
    Executor executor = new Executor() {
        @Override//from  www . j  ava2s . 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("attend_rate")) {
                    db.getCollection(s).drop();
                }
            }
            DBCollection dbCollection = db.getCollection("attend_rate");
            ProfilesIni pi = new ProfilesIni();
            FirefoxProfile profile = pi.getProfile("default");
            WebDriver driver = new FirefoxDriver(profile);
            driver.manage().window().maximize();
            driver.manage().timeouts().pageLoadTimeout(3, TimeUnit.SECONDS);
            //                driver.setJavascriptEnabled(false);
            driver.get(datum.getUrl());
            //                System.out.println(driver.getPageSource());
            driver.findElement(By.xpath("//*[@id='seat_city']")).click();
            driver.switchTo().window(driver.getWindowHandle());

            int city_num = driver.findElements(By.xpath("//div[@id='all-citys']/div/ul/li/a")).size();
            for (int i = 0; i < city_num; i++) {
                System.out.println("A city chosen" + i);
                System.out.println(
                        driver.findElements(By.xpath("//div[@id='all-citys']/div/ul/li/a")).get(i).getText());
                String city = driver.findElements(By.xpath("//div[@id='all-citys']/div/ul/li/a")).get(i)
                        .getText();
                ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);",
                        driver.findElements(By.xpath("//div[@id='all-citys']/div/ul/li/a")).get(i));
                ((JavascriptExecutor) driver).executeScript("window.scrollBy(0, -250)", "");
                Thread.sleep(1000);
                new Actions(driver)
                        .moveToElement(
                                driver.findElements(By.xpath("//div[@id='all-citys']/div/ul/li/a")).get(i))
                        .click().perform();
                driver.switchTo().window(driver.getWindowHandle());
                //                System.out.println(driver.findElement(By.xpath("//span[@class='today']/em")).getText());
                System.out.println(driver.findElement(By.xpath("//span[@class='today']")).getText());
                for (int j = 0; j < driver
                        .findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c1 lineDot']"))
                        .size(); j++) {
                    System.out.println(driver
                            .findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c1 lineDot']"))
                            .get(j).getText());
                    System.out.println(
                            driver.findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c2 red']"))
                                    .get(j).getText());
                    System.out.println(
                            driver.findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c3 gray']"))
                                    .get(j).getText());
                    BasicDBObject dbObject = new BasicDBObject();
                    dbObject.append("title", driver.findElement(By.xpath("//span[@class='today']")).getText())
                            .append("city", city)
                            .append("mov_cnname",
                                    driver.findElements(
                                            By.xpath("//div[@id='seat_table']//ul//li[@class='c1 lineDot']"))
                                            .get(j).getText())
                            .append("boxoffice_rate", driver
                                    .findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c2 red']"))
                                    .get(j).getText())
                            .append("visit_pershow", driver
                                    .findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c3 gray']"))
                                    .get(j).getText());
                    dbCollection.insert(dbObject);
                }
                System.out.println("new city list to choose");
                new Actions(driver).moveToElement(driver.findElement(By.xpath("//*[@id='seat_city']"))).click()
                        .perform();
                driver.switchTo().window(driver.getWindowHandle());
                Thread.sleep(500);
            }
            driver.close();
            driver.quit();
            mongoClient.close();
        }
    };

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

From source file:cn.edu.hfut.dmic.webcollector.example.FirefoxSelenium4.java

License:Open Source License

public static void main(String[] args) throws Exception {
    Executor executor = new Executor() {
        @Override//  w w  w.j  a va 2 s.  c o 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("rankings_am")) {
                    db.getCollection(s).drop();
                }
            }
            DBCollection dbCollection = db.getCollection("attend_rate");
            ProfilesIni pi = new ProfilesIni();
            FirefoxProfile profile = pi.getProfile("default");
            WebDriver driver = new FirefoxDriver(profile);
            driver.manage().timeouts().pageLoadTimeout(3, TimeUnit.SECONDS);
            //                driver.setJavascriptEnabled(false);
            driver.get(datum.getUrl());
            //                System.out.println(driver.getPageSource());
            List<WebElement> movie_name = driver
                    .findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c1 lineDot']"));
            List<WebElement> boxoffice_rate = driver
                    .findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c2 red']"));
            List<WebElement> visit_pershow = driver
                    .findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c3 gray']"));
            WebElement title = driver.findElement(By.xpath("//span[@class='today']/em"));
            WebElement title2 = driver.findElement(By.xpath("//span[@class='today']"));
            System.out.println(title.getText());
            System.out.println(title.getText());
            for (int i = 0; i < movie_name.size(); i++) {
                System.out.println(movie_name.get(i).getText());
                System.out.println(boxoffice_rate.get(i).getText());
                System.out.println(visit_pershow.get(i).getText());
                //                   BasicDBObject dbObject = new BasicDBObject();
                //                  dbObject.append("title", title).append("rank", amList.get(0)).append("mov_cnname", cn_name).append("mov_enname", en_name).append("toweek_rev", amList.get(2)).append("total_rev", amList.get(3)).append("val_week", amList.get(4));
                //                   dbCollection.insert(dbObject);
            }
            driver.quit();

        }
    };

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

From source file:co.edu.icesi.i2t.slrtools.bib.transformations.TransformBibACM.java

License:Open Source License

/**
 * Funcion principal para la transformacion de los archivos html en un solo
 * arhivo consolidado BIB, la funcion se encarga de extraer del html cada
 * link de articulo, despues de tener el listado de url se dispone con la
 * ayuda de selenium webdriver el ingreso a cada url y descargar el BIBtex
 * para finalizar con la union de todos en un solo archivo BIB
 *
 * @param sourceFilesPath String con la ruta de la carpeta donde se
 * encuentran los archivos html a transformas
 * @param targetFilePath String con la ruta fisica del directorio donde se
 * guardara el archivo consolodidao//from  w ww . j av a  2 s. c  o  m
 * @param targetFileName
 */
public static boolean transformFiles(String sourceFilesPath, String targetFilePath, String targetFileName) {
    boolean bibFileCreated = false;

    System.out.println("");
    System.out.println("-----------------------------");
    System.out.println("Generating BibTeX for ACM Digital Library results...");
    System.out.println("");

    String bibContent = "";
    List<String> urls = extractURL(sourceFilesPath);
    FirefoxProfile profile = new FirefoxProfile();
    WebDriver webDriver = new FirefoxDriver(profile);
    for (int i = 0; i < urls.size(); i++) {
        try {
            System.out.println("[INFO] Retrieving BibTeX from URL: " + urls.get(i));
            String idFile = urls.get(i).split("id=")[1].split("&")[0];
            idFile = idFile.substring(idFile.indexOf(".") + 1, idFile.length());
            String url = (urls.get(i));
            webDriver.get(url);
            WebElement bibField = (new WebDriverWait(webDriver, 10))
                    .until(ExpectedConditions.presenceOfElementLocated(By.linkText("BibTeX")));
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {

            }
            bibField.click();
            WebElement textBib = (new WebDriverWait(webDriver, 10))
                    .until(ExpectedConditions.presenceOfElementLocated(By.id(idFile)));
            String reference = textBib.getText();
            String referenceAbstract = webDriver.findElement(By.id("abstract")).getText();
            referenceAbstract = "abstract = {" + referenceAbstract + "}}" + System.lineSeparator();
            bibContent += reference.substring(0, reference.length() - 2) + referenceAbstract;
            //Thread.sleep(10000);
            //tempurl.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        } catch (TimeoutException e) {
            System.out.println(
                    "[ERROR] Failed to retrieve BibTex. The application may have been blocked by ACM Digital Library. Try again later.");
        } catch (Exception e) {
            System.out.println("[ERROR] Failed to retrieve BibTeX. " + e.getMessage());
        }
    }
    webDriver.quit();
    try {
        saveBibFile(bibContent, targetFilePath, targetFileName);
        if (!bibContent.equals("")) {
            bibFileCreated = true;
        }
    } catch (Exception e) {
        System.out.println("[ERROR] Failed to create BibTeX file." + e.getMessage());
    }
    System.out.println("-----------------------------");
    return bibFileCreated;
}

From source file:co.edu.icesi.i2t.slrtools.webdrivers.WebDriverACM.java

License:Open Source License

/**
 * Funcion que se encarga de realizar automaticamente la busqueda en la base
 * de datos ACM Digital Library conforme a una cadena de busqueda
 * introducida, ACM digital library no permite la descarga de ningun archivo
 * del resultado de la busqueda, por tal razn, se descarga el codigo fuente
 * de la pagina en el source del proyecto el cual posteriormente es usado
 * para la extraccin de la informacin y construccion del BIB con los
 * resultados obtenidos/*from  w  w  w  . j a v a 2  s  .c  om*/
 *
 * @param searchStrings este parametro es la cadena de busqueda que retorna
 * la funcion mixACM#mixWords2, cada cadena de busqueda esta separada por ;
 * @param url este paremetro es el URL de la busqueda avanzada de ACM
 * Digital Library
 * @see mixWords.mixACM#mixWords2(java.lang.String, java.lang.String)
 */
public static void searchWeb(String searchStrings, String url) {
    /* a esta funcion se debe mejorar
     * 1: validar el boton siguiente sin try catch, mejorar el manejo de las expeciones
     */
    System.out.println("");
    System.out.println("-----------------------------");
    System.out.println("Searching ACM Digital Library...");
    System.out.println("Search strings: " + searchStrings + "");
    System.out.println("");

    FirefoxProfile profile = new FirefoxProfile();
    WebDriver webDriver = new FirefoxDriver(profile);
    String[] strings = searchStrings.split(";");
    for (int i = 0; i < strings.length; i++) {
        try {
            webDriver.get(url);

            WebElement searchField = webDriver.findElement(By.name("within"));
            searchField.click();
            searchField.sendKeys(strings[i]);

            WebElement buttonSearch = webDriver.findElement(By.name("Go"));
            buttonSearch.click();

            List<WebElement> stringResult = webDriver
                    .findElements(By.xpath("//span[contains(@style, 'background-color:yellow')]"));
            if (!stringResult.isEmpty()) {
                System.out.println(
                        "[WARNING] Search string " + (i + 1) + ": " + strings[i] + " retrieves no results");
            } else {
                int counter = 1;
                try {
                    WebElement nextField = null;
                    do {
                        String sourceCode = webDriver.getPageSource();
                        File targetDirectory = new File("files" + File.separator + Database.ACM.getName());
                        targetDirectory.mkdir();
                        try (PrintWriter file = new PrintWriter(
                                "files" + File.separator + Database.ACM.getName() + File.separator
                                        + "searchResults_" + i + "_" + counter + ".html",
                                "UTF-8")) {
                            file.print(sourceCode);
                        }
                        nextField = (new WebDriverWait(webDriver, 10))
                                .until(ExpectedConditions.presenceOfElementLocated(By.linkText("next")));
                        try {
                            Thread.sleep(10000);
                        } catch (InterruptedException e) {

                        }
                        nextField.click();
                        counter++;
                    } while (true);
                } catch (NoSuchElementException | TimeoutException | NullPointerException e) {
                    System.out.println("[INFO] Search string " + (i + 1) + ": " + strings[i] + " has "
                            + counter + (counter == 1 ? " result" : " results") + "returned");
                }
            }
        } catch (FileNotFoundException | UnsupportedEncodingException e) {
            System.out.println(
                    "[ERROR] Search string " + (i + 1) + ": " + strings[i] + " failed. " + e.getMessage());
        } catch (NoSuchElementException e) {
            System.out.println(
                    "[ERROR] The application has been blocked by ACM Digital Library. Try again later.");
        }
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {

        }
    }
    webDriver.quit();
    System.out.println("[INFO] Finished search in ACM Digital Library");
    System.out.println("-----------------------------");
}

From source file:com.adasasistemas.pilot.webtest3.NewSeleneseIT.java

@Test
public void testSimple() throws Exception {
    // Create a new instance of the Firefox driver
    // Notice that the remainder of the code relies on the interface, 
    // not the implementation.
    FirefoxProfile fp = new FirefoxProfile();

    //   fp.setPreference("browser.startup.homepage", URL);
    // fp.setPreference("startup.homepage_welcome_url", URL);
    //fp.setPreference("startup.homepage_welcome_url.additional", URL);
    FirefoxBinary fb = new FirefoxBinary(new File(NAVIGATOR));
    WebDriver driver = new FirefoxDriver(fb, fp);

    // And now use this to visit NetBeans
    //  driver.get("http://www.netbeans.org");
    // Alternatively the same thing can be done like this
    // driver.navigate().to("http://www.netbeans.org");
    // Check the title of the page
    // Wait for the page to load, timeout after 10 seconds
    driver.navigate().to("http://localhost:8085/webtest3");
    //* driver.navigate().refresh();
    //  driver.get("http://localhost:8085/webtest3");
    //    System.out.println(driver.getPageSource());

    (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
        @Override//from ww  w .  jav  a  2s  . c  o  m
        public Boolean apply(WebDriver d) {
            System.out.println(d.getPageSource());
            return d.getPageSource().contains("Hello");
        }
    });

    //Close the browser
    driver.quit();
}

From source file:com.amazon.alexa.avs.AVSApp.java

License:Open Source License

/**
 * Authenticates this client to LWA.//from  www.j a  v a  2  s.c o m
 * 
 * @param url Login URL to perform authentification to.
 */
private void authenticate(final String url) {
    log.info("Registration URL = {}", url);
    final WebDriver driver = createDriver();
    driver.get(url);
    // TODO : Consider adding sleep to ensure page loading.
    authenticate(driver);
    log.info("Authentification done, check for agreemennt validation");
    // TODO : Consider adding sleep to ensure page loading.
    validateAgreement(driver);
    log.info(driver.getPageSource());
    log.info("Waiting for authentification callback to be triggered");
    // TODO : Consider adding sleep to ensure page loading.
    driver.quit();
}

From source file:com.asimihsan.handytrowel.network.HTMLFetcher.java

License:Open Source License

public String getPageSource(final String url) throws TimeoutException {

    // Make the Selenium WebDriver logs be quiet
    phantomJsLogger.setLevel(Level.OFF);

    DesiredCapabilities desiredCapabilities = DesiredCapabilities.phantomjs();
    // What other CLI args there are: http://phantomjs.org/api/command-line.html
    // Where the cache goes on Mac OS X: ~/Library/Application\ Support/Ofi\ Labs/PhantomJS/
    // Other cache locations: https://groups.google.com/forum/#!topic/phantomjs/8GYaXKmowj0
    desiredCapabilities.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS,
            new String[] { "--ignore-ssl-errors=yes", "--load-images=no", "--disk-cache=true",
                    "--max-disk-cache-size=size=51200" });
    final WebDriver driver = new PhantomJSDriver(desiredCapabilities);

    // doesn't work, keep as reference.
    //driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    try {//from   w  ww .  j av  a2s  . com
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                driver.get(url);
            }
        });
        t.start();
        try {
            t.join(timeoutMillis);
        } catch (InterruptedException e) {
        }
        if (t.isAlive()) {
            System.out.println("Timeout for HTTP GET to: " + url);
            t.interrupt();
            throw new TimeoutException();
        }
        String pageSource = driver.getPageSource();
        return pageSource;
    } finally {
        driver.quit();
    }
}

From source file:com.automationpractice.tests.SaleBanners.java

public static void main(String[] args) {

    //open browser
    System.setProperty("webdriver.chrome.driver", "D:\\selenium test lib\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.get("http://automationpractice.com");

    //test://from ww w. j  a  v a  2s  . com
    driver.findElement(By.xpath(".//*[@id='htmlcontent_top']/ul/li[1]/a/img")).click();
    driver.navigate().back();
    driver.findElement(By.xpath(".//*[@id='htmlcontent_top']/ul/li[2]/a/img")).click();
    driver.navigate().back();
    driver.findElement(By.xpath(".//*[@id='htmlcontent_home']/ul/li[1]/a/img")).click();
    driver.navigate().back();
    driver.findElement(By.xpath(".//*[@id='htmlcontent_home']/ul/li[2]/a/img")).click();
    driver.navigate().back();
    driver.findElement(By.xpath(".//*[@id='htmlcontent_home']/ul/li[3]/a/img")).click();
    driver.navigate().back();
    driver.findElement(By.xpath(".//*[@id='htmlcontent_home']/ul/li[4]/a/img")).click();
    driver.navigate().back();
    driver.findElement(By.xpath(".//*[@id='htmlcontent_home']/ul/li[5]/a/img")).click();

    driver.quit();

}