Example usage for org.openqa.selenium WebElement sendKeys

List of usage examples for org.openqa.selenium WebElement sendKeys

Introduction

In this page you can find the example usage for org.openqa.selenium WebElement sendKeys.

Prototype

void sendKeys(CharSequence... keysToSend);

Source Link

Document

Use this method to simulate typing into an element, which may set its value.

Usage

From source file:cn.edu.bistu.spider.sina.WeiboCN.java

/**
 * ??cookieweibo.cnweibo.com weibo.cn????
 * @param username ???//w  w w  .  j  a  va 2 s.  co  m
 * @param password ??
 * @return
 * @throws Exception
 */
@SuppressWarnings("deprecation")
public static String getSinaCookie(String username, String password) throws Exception {
    String result = "";
    HtmlUnitDriver driver = new HtmlUnitDriver();
    while (!result.contains("gsid_CTandWM")) {
        driver.setJavascriptEnabled(true);
        driver.get("http://login.weibo.cn/login/");
        WebElement ele = driver.findElementByCssSelector("img");
        String src = ele.getAttribute("src");
        String cookie = concatCookie(driver);
        HttpRequest request = new HttpRequest(src);
        request.setCookie(cookie);
        HttpResponse response = request.getResponse();
        ByteArrayInputStream is = new ByteArrayInputStream(response.getContent());
        BufferedImage img = ImageIO.read(is);
        is.close();
        ImageIO.write(img, "png", new File("result.png"));
        String userInput = new CaptchaFrame(img).getUserInput();
        WebElement mobile = driver.findElementByCssSelector("input[name=mobile]");
        mobile.sendKeys(username);
        WebElement pass = driver.findElementByCssSelector("input[name^=password]");
        pass.sendKeys(password);
        WebElement code = driver.findElementByCssSelector("input[name=code]");
        code.sendKeys(userInput);
        WebElement rem = driver.findElementByCssSelector("input[name=remember]");
        rem.click();
        WebElement submit = driver.findElementByCssSelector("input[name=submit]");
        submit.click();
        result = concatCookie(driver);
    }
    driver.close();
    return result;
}

From source file:cn.hxh.springside.test.functional.Selenium2.java

License:Apache License

/**
 * Element.//w w  w  .j  ava 2  s.c  o m
 */
public void type(By by, String text) {
    WebElement element = driver.findElement(by);
    element.clear();
    element.sendKeys(text);
}

From source file:cn.newtouch.util.test.utils.SeleniumUtils.java

License:Apache License

/**
 * Selnium1.0./* w ww  .j a va  2 s .  c om*/
 */
public static void type(WebElement element, String text) {
    element.clear();
    element.sendKeys(text);
}

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   ww w.jav a  2s .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:co.edu.icesi.i2t.slrtools.webdrivers.WebDriverIEEEComputerScience.java

License:Open Source License

/**
 * //from  www  .j  a v  a 2  s  . co m
 * @param cadenasBusqueda
 * @param direccionBusqueda
 */
public static void searchWeb(String cadenasBusqueda, String direccionBusqueda) {
    /* a esta funcion se debe mejorar
     * 1: automatizar las preferencias para la descarga automatica
     * 2: la ruta de descarga
     * 3: el cierre del navegador al finalizar la ultima descarga*/
    System.out.println("----------inicia busqueda web IEEE Computer Society----------");
    System.out.println("Cadena de palabras a buscar: " + cadenasBusqueda);
    System.out.println("------------------------------------------------------");
    FirefoxProfile profile = new FirefoxProfile();
    WebDriver url = new FirefoxDriver(profile);
    String[] lcadenasBusqueda = cadenasBusqueda.split(";");
    for (int i = 0; i < lcadenasBusqueda.length; i++) {
        try {
            url.get(direccionBusqueda);
            WebElement searchField = url.findElement(By.name("queryText1"));
            WebElement buttonSearch = url.findElement(By.id("searchButton"));
            searchField.click();
            searchField.sendKeys(lcadenasBusqueda[i]);
            buttonSearch.click();
            WebElement selectField = url.findElement(By.id("select1"));
            WebElement buttonField = url.findElement(By.id("form1Button"));
            selectField.sendKeys("100");
            buttonField.click();
            try {
                WebElement stringResult = url
                        .findElement(By.xpath("//div[contains(@class, 'searchwhitebox')]"));
                System.out.println("Busqueda: " + i + " cadena de busqueda:" + lcadenasBusqueda[i] + " - "
                        + stringResult.getText());
                //String sourceCode=url.getPageSource();
                //PrintWriter archivo = new PrintWriter("busquedasIEEECS/"+lcadenasBusqueda[i]+".html", "UTF-8");
                //archivo.print(sourceCode);
                //archivo.close();              
            } catch (Exception e) {
                System.out.println("[OJO]" + " Busqueda: " + i + " la cadena de busqueda: "
                        + lcadenasBusqueda[i] + " no trae resultados");
            }
        } catch (Exception e) {
            System.out
                    .println("excepcion busqueda cadena: " + lcadenasBusqueda[i] + " , motivo excepcion: " + e);
        }
    }
    //url.quit();
    System.out.println("----------fin busqueda web IEEE Computer Society----------");
}

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

License:Open Source License

/**
 * Funcion que se encarga de realizar automaticamente la busqueda en la base
 * de datos IEEEXplore conforme a una cadena de busqueda introducida, la
 * automatizacion nos permite descargar los CSV que IEEEXplore dispone con
 * el resultaod de las busquedas, la ruta donde se guardan los archivos
 * dependen de la seleccin del usuario, si por alguna razon el resultado de
 * la busqueda es mayor a 2000 datos, el buscador solo deja descargar los
 * primeros 2000 ordenados por importancia de acuerdo a las politicas de
 * IEEEXplore, los archivos descargados posteriormente son procesadas para
 * la construccion del BIB con los resultados obtenidos.
 *
 * @param searchStrings este parametro es la cadena de busqueda que retorna
 * la funcion mixIEEEXplore#mixWords, cada cadena de busqueda esta separada
 * por ;//from   ww w .  j a v a  2  s  .  c om
 * @param url este paremetro es el URL de la busqueda avanzada de IEEEXplore
 * @see mixWords.mixIEEEXplore#mixWords(java.lang.String, java.lang.String)
 */
public static void searchWeb(String searchStrings, String url) {
    System.out.println("");
    System.out.println("-----------------------------");
    System.out.println("Searching IEEE Xplore Digital Library...");
    System.out.println("Search strings: " + searchStrings + "");
    System.out.println("");

    String workingDir = System.getProperty("user.dir");

    File targetDirectory = new File("files" + File.separator + Database.IEEE_XPLORE.getName());
    targetDirectory.mkdir();

    FirefoxProfile profile = new FirefoxProfile();

    profile.setPreference("browser.download.folderList", 2);
    profile.setPreference("browser.download.manager.showWhenStarting", false);
    profile.setPreference("browser.download.dir",
            workingDir + File.separator + "files" + File.separator + Database.IEEE_XPLORE.getName());
    profile.setPreference("browser.download.useDownloadDir", true);
    profile.setPreference("browser.helperapps.neverAsk.saveToDisk", "application/x-latex;text/csv");
    profile.setPreference("browser.helperApps.alwaysAsk.force", false);
    profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
    profile.setPreference("browser.download.manager.closeWhenDone", true);

    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.id("expression-textarea"));
            WebElement buttonSearch = webDriver.findElement(By.id("submit-search"));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {

            }
            searchField.click();
            searchField.sendKeys(strings[i]);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {

            }
            buttonSearch.click();
            try {
                WebElement exportField = (new WebDriverWait(webDriver, 10))
                        .until(ExpectedConditions.presenceOfElementLocated(By.id("popup-export-results")));
                WebElement stringResult = webDriver
                        .findElement(By.xpath("//div[contains(@id, 'content')]/span"));
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {

                }
                exportField.click();
                System.out.println("[INFO] Search string " + (i + 1) + " " + strings[i] + " "
                        + stringResult.getText());
                WebElement exportButton = (new WebDriverWait(webDriver, 10))
                        .until(ExpectedConditions.presenceOfElementLocated(By.id("export_results_ok")));
                exportButton.click();
            } catch (Exception e) {
                System.out.println(
                        "[WARNING] Search string " + (i + 1) + " " + strings[i] + " retrieves no results");
            }
        } catch (Exception e) {
            System.out.println(
                    "[ERROR] Search string " + (i + 1) + " " + strings[i] + " failed. " + e.getMessage());
        }
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {

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

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

License:Open Source License

/**
 * Funcion que se encarga de realizar automaticamente la busqueda en la base
 * de datos ScienceDirect conforme a una cadena de busqueda introducida, la
 * automatizacion nos permite descargar los BIB que ScienceDirect dispone
 * con el resultaod de las busquedas, la ruta donde se guardan losr archivos
 * dependen de la seleccin del usuario, si por alguna razon el resultado de
 * la busqueda es mayor a 1000 datos, el buscador solo deja descargar los
 * primeros 1000 ordenados por importancia de acuerdo a las politicas de
 * ScienceDirect, los archivos descargados posteriormente son procesadas
 * para la construccion del BIB consolodidado con los resultados obtenidos.
 *
 * @param searchStrings este parametro es la cadena de busqueda que retorna
 * la funcion mixScienceDirect#mixWords, cada cadena de busqueda esta
 * separada por ;/*www . j a  va2  s .c  o  m*/
 * @param url este paremetro es el URL de la busqueda experta de
 * ScienceDirect
 * @see mixWords.mixScienceDirect#mixWords(java.lang.String,
 * java.lang.String)
 */
public static void searchWeb(String searchStrings, String url) {
    System.out.println("");
    System.out.println("-----------------------------");
    System.out.println("Searching Science Direct...");
    System.out.println("Search strings: " + searchStrings + "");
    System.out.println("");

    String workingDir = System.getProperty("user.dir");

    File targetDirectory = new File("files" + File.separator + Database.SCIENCE_DIRECT.getName());
    targetDirectory.mkdir();

    FirefoxProfile profile = new FirefoxProfile();

    profile.setPreference("browser.download.folderList", 2);
    profile.setPreference("browser.download.manager.showWhenStarting", false);
    profile.setPreference("browser.download.dir",
            workingDir + File.separator + "files" + File.separator + Database.SCIENCE_DIRECT.getName());
    profile.setPreference("browser.download.useDownloadDir", true);
    profile.setPreference("browser.helperapps.neverAsk.saveToDisk", "application/x-latex;text/csv");
    profile.setPreference("browser.helperApps.alwaysAsk.force", false);
    profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
    profile.setPreference("browser.download.manager.closeWhenDone", true);
    profile.setPreference("browser.download.panel.shown", true);

    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("SearchText"));
            //              WebElement searchField = (new WebDriverWait(webDriver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.name("SearchText")));
            WebElement submitSearch = webDriver.findElement(By.name("RegularSearch"));
            //              WebElement submitSearch = (new WebDriverWait(webDriver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.name("RegularSearch")));
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {

            }
            searchField.click();
            searchField.sendKeys(strings[i]);
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {

            }
            submitSearch.click();
            try {
                WebElement exportButton = (new WebDriverWait(webDriver, 10)).until(ExpectedConditions
                        .presenceOfElementLocated(By.cssSelector("span.down_sci_dir.exportArrow")));
                WebElement stringResult = webDriver
                        .findElement(By.xpath("//h1[contains(@class, 'queryText')]/strong"));
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {

                }
                exportButton.click();
                System.out.println("[INFO] Search string " + (i + 1) + " " + strings[i] + " "
                        + stringResult.getText());
                WebElement bibTex = webDriver.findElement(By.id("BIBTEX"));
                bibTex.click();
                WebElement export = webDriver.findElement(By.id("export_button"));
                export.click();
            } catch (Exception e) {
                System.out.println(
                        "[WARNING] Search string " + (i + 1) + " " + strings[i] + " retrieves no results");
            }
        } catch (Exception e) {
            System.out.println(
                    "[ERROR] Search string " + (i + 1) + " " + strings[i] + " failed. " + e.getMessage());
        }
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {

        }
    }
    //   webDriver.quit();
    System.out.println("[INFO] Finished search in Science Direct");
    System.out.println("-----------------------------");
}

From source file:co.flexmod.selenium.example.integration.HelloWorldPage.java

License:Apache License

public void setNameValue(String value) {
    WebElement txtName = webDriver.findElement(By.id(TXT_NAME));
    txtName.clear();
    txtName.sendKeys(value);
}

From source file:com.alehuo.wepas2016projekti.test.UiTest.java

License:Open Source License

/**
 *
 *//*from  www . j  av a2  s .  co  m*/
@Test
public void uudenKuvanJakaminenToimii() {

    goTo("http://localhost:" + port);

    assertTrue("\nError: ei lydy 'Kirjaudu sisn' -teksti\n" + pageSource() + "\n",
            pageSource().contains("Kirjaudu sisn"));

    //admin -tunnuksilla sisn
    fill(find("#username")).with("admin");
    fill(find("#password")).with("admin");
    //        webDriver.findElement(By.id("username")).sendKeys("admin");
    //        webDriver.findElement(By.id("password")).sendKeys("admin");

    System.out.println("USERNAME VALUE: " + find("#username").getValue());
    System.out.println("PASSWORD VALUE: " + find("#password").getValue());

    //Lhet lomake
    submit(find("#loginForm"));

    //Nyt ollaan etusivulla
    System.out.println("\n\n\n\n\n\n\n\n" + pageSource() + "\n\n\n\n\n\n\n\n");
    assertTrue("\nError: ei lydy 'Syte' -teksti \n" + pageSource() + "\n",
            pageSource().contains("Syte"));

    //Klikkaa "plus" -nappia
    click(find("#uploadBtn").first());

    //Nyt ollaan Upload -sivulla
    assertTrue("\nError: ei lydy 'Jaa kuva' -teksti \n" + pageSource() + "\n",
            pageSource().contains("Jaa kuva"));

    //Lis kuvaus
    String description = UUID.randomUUID().toString().substring(0, 8);
    fill(find("#imageDesc")).with(description);

    //Kuvatiedosto
    WebElement upload = webDriver.findElement(By.id("imgUploadInput"));

    upload.sendKeys("testi.jpg");

    //Klikkaa submit
    webDriver.findElement(By.id("uploadSubmitBtn")).click();

    //Nyt ollaan etusivulla, tarkistetaan ett kuva listtiin onnistuneesti
    assertTrue("\nError: ei lydy ladatun kuvan kuvausta \n" + pageSource() + "\n",
            pageSource().contains(description));

    assertEquals("\nError: kuvia ei ole listassa kuusi \n" + pageSource() + "\n", 6,
            imageService.findAllImages().size());
}

From source file:com.algomedica.service.AlgomedicaTest.java

@Test
public void Login() throws InterruptedException {

    WebElement Username = driver.findElement(By.cssSelector("[name='username']"));
    Username.sendKeys("koutuk");

    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

    WebElement password = driver.findElement(By.cssSelector("[name='password']"));
    password.sendKeys("koutuk");

    driver.findElement(By.cssSelector(".btn.btn-lg.btn-success.btn-block")).click();

}