Example usage for org.openqa.selenium WebDriver findElement

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

Introduction

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

Prototype

@Override
WebElement findElement(By by);

Source Link

Document

Find the first WebElement using the given method.

Usage

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 w  w w. j  a v a2s .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 ;//from w ww .j a  v a 2 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.edu.icesi.i2t.slrtools.webdrivers.WebDriverSpringerLink.java

License:Open Source License

/**
 * Funcion que se encarga de realizar automaticamente la busqueda en la base
 * de datos SpringerLink conforme a una cadena de busqueda introducida, la
 * automatizacion nos permite descargar los CSV que SpringerLink 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
 * SpringerLink, 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 ;/*  w  w  w. ja  v a  2s . co  m*/
 * @param url este paremetro es el URL de la busqueda experta de
 * ScienceDirect, el url es incompleto y se complementa con la informacion
 * del primer parametro
 * @see mixWords.mixSpringer#mixWords(java.lang.String, java.lang.String)
 */
public static void searchWeb(String searchStrings, String url) {
    /* 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("");
    System.out.println("-----------------------------");
    System.out.println("Searching Springer Link...");
    System.out.println("Search strings: " + searchStrings);
    System.out.println("");

    FirefoxProfile profile = new FirefoxProfile();

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

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

    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.SPRINGER_LINK.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 + strings[i]);
            //WebElement searchField = url.findElement(By.name("title-is"));
            //WebElement buttonSearch = url.findElement(By.id("submit-advanced-search"));
            //searchField.click();
            //searchField.sendKeys(lcadenasBusqueda[i]);
            //buttonSearch.click();
            try {
                WebElement exportField = (new WebDriverWait(webDriver, 10)).until(ExpectedConditions
                        .presenceOfElementLocated(By.cssSelector("#tool-download > span.icon")));
                WebElement stringResult = webDriver.findElement(
                        By.xpath("//h1[contains(@class, 'number-of-search-results-and-search-terms')]/strong"));
                System.out.println("[INFO] Search string " + (i + 1) + " " + strings[i] + " has "
                        + stringResult.getText() + " result(s) returned");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {

                }
                exportField.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());
        }
    }
    //   webDriver.quit();
    System.out.println("[INFO] Finished search in Springer Link");
    System.out.println("-----------------------------");
}

From source file:com.acme.ui.LoginScreenWebDriverTestCase.java

License:Apache License

private void checkElementPresent(WebDriver driver, By by, String errorMsg) {
    try {// w w  w  . ja  v  a2 s. c  o  m
        Assert.assertTrue(errorMsg, driver.findElement(by) != null);
    } catch (NoSuchElementException e) {
        Assert.fail(errorMsg);
    }
}

From source file:com.alfonsogalvanmadera.robot.Leer.java

/**
 * @param args the command line arguments
 *//*from ww  w. j  ava 2  s.  c o  m*/
public static void main(String[] args) throws Exception {
    // TODO code application logic here
    DAOCadena2 daoc = new DAOCadena2();
    DAOCliente2 daoc1 = new DAOCliente2();
    DAOAccion2 daoa = new DAOAccion2();
    DAODato2 daod = new DAODato2();

    Cadena2 cadena = daoc.bucarCadena(3);
    Cliente2 c = daoc1.buscarCliente(3);
    Accion2 a = daoa.bucarAccion2(3);
    Dato2 d = daod.buscarDato2(3);
    //cad
    WebDriver driver = new FirefoxDriver();
    driver.get(cadena.getUrl());
    //driver.findElement(By.name(cadena.getUrl()));
    driver.findElement(By.id(d.getCampoLogin())).sendKeys(c.getUsuario());

    driver.findElement(By.id(d.getCampoPass())).sendKeys(c.getPass());
    driver.findElement(By.name(a.getAccion())).click();

}

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

License:Open Source License

/**
 * Performs amazon LWA login using the given <tt>driver</tt>.
 * /*from   w  ww  .jav  a2  s.c  om*/
 * @param driver Driver which is already configured to LWA login page.
 */
private void authenticate(final WebDriver driver) {
    log.debug("Title : {}", driver.getTitle());
    new WebDriverWait(driver, 1000)
            .until(ExpectedConditions.and(ExpectedConditions.presenceOfElementLocated(By.id("ap_email")),
                    ExpectedConditions.presenceOfElementLocated(By.id("ap_password"))));
    log.info("Auto logging in to LWA");
    final WebElement username = driver.findElement(By.id("ap_email"));
    final WebElement password = driver.findElement(By.id("ap_password"));
    username.sendKeys(deviceConfig.getLWAUsername());
    password.sendKeys(deviceConfig.getLWAPassword());
    final WebElement button = driver.findElement(By.tagName("button"));
    button.click();
}

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

License:Open Source License

/**
 * Validates usage agreement if available.
 * //from   w  w w .j ava  2s.c  o  m
 * @param driver Driver which is already configured to usage agreement.
 */
private void validateAgreement(final WebDriver driver) {
    try {
        // TODO : Consider using driver wait with timeout.
        final WebElement button = driver.findElement(By.name("consentApproved"));
        button.click();
    } catch (final NoSuchElementException e) {
        log.info("Agreement not found, abort validation");
    }
}

From source file:com.amolik.scrapers.OdishaRationCardScraper.java

public static void processAllDistricts(WebDriver driver) throws InterruptedException {

    Select districtSelect = new Select(driver.findElement(By.name(Constants.DDL_DISTRICT)));
    List<WebElement> districtsList = districtSelect.getOptions();

    // Prepare List of names of districts
    for (WebElement districtElement : districtsList) {

        districtsNameList.add(districtElement.getText());
    }/*from w  w w .ja  v  a  2s.co m*/

    int districtSize = districtsList.size();

    // Remove this during production
    //districtSize=2;
    int startDistrictIndex = new Integer(AmolikProperties.getProperty("odisha_ration.startDistrictIndex"))
            .intValue();

    for (int districtIndex = startDistrictIndex; districtIndex < districtSize; districtIndex++) {

        processDistrict(driver, districtIndex);
        //TimeUnit.SECONDS.sleep(3);
    }
}

From source file:com.amolik.scrapers.OdishaRationCardScraper.java

public static void processDistrict(WebDriver driver, int districtIndex) {

    Select districtSelect = new Select(driver.findElement(By.name(Constants.DDL_DISTRICT)));
    districtSelect.selectByIndex(districtIndex);
    try {/*  www.  j a  v  a 2s .  c o  m*/
        TimeUnit.SECONDS.sleep(3);
    } catch (InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    int blockSize = getRefreshedBlockSelect(driver, districtIndex).getOptions().size();

    if (logger.isDebugEnabled()) {
        logger.debug("processDistrict blockSize=" + blockSize); //$NON-NLS-1$
    }

    // Remove during production
    //blockSize =2;

    int startBlockIndex = new Integer(AmolikProperties.getProperty("odisha_ration.startBlockIndex")).intValue();
    ArrayList<OdishaRationCardBean> beanList = new ArrayList();

    for (int blockIndex = startBlockIndex; blockIndex < blockSize; blockIndex++) {

        Select blockSelect = getRefreshedBlockSelect(driver, districtIndex);
        List<WebElement> blocksList = blockSelect.getOptions();
        WebElement block = blocksList.get(blockIndex);

        if (logger.isDebugEnabled()) {

            logger.debug("processDistrict(WebDriver, int) - block=" + block.getText()); //$NON-NLS-1$
        }

        String blockValue = block.getAttribute(Constants.LOWERCASE_VALUE);

        if (logger.isDebugEnabled()) {

            logger.debug("processDistrict(WebDriver, int) - " + districtIndex + "|"
                    + block.getAttribute(Constants.LOWERCASE_VALUE) + "|" + block.getText()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        }
        processBlock(driver, districtIndex, blockIndex, blockValue, block.getText(), beanList);
    }

    // Create new Directory if not exists
    String districtName = districtsNameList.get(districtIndex);
    String excelDestDirName = AmolikProperties.getProperty("odisha_ration.excelOutputDir");
    new File(excelDestDirName).mkdirs();

    String excelDestFileName = excelDestDirName + System.getProperty("file.separator") + districtName
            + excelFileExtension;

    if (logger.isInfoEnabled()) {

        logger.info("writing to excel " + districtIndex + "|" + districtName + "| toal recordCount="
                + (beanList.size()));
    }

    ExcelUtil.generateExcelFromBean(beanList, excelTemplateFileName, excelTemplateFileName, excelDestFileName,
            "rationCard");

}

From source file:com.amolik.scrapers.OdishaRationCardScraper.java

public static Select getRefreshedBlockSelect(WebDriver driver, int districtIndex) {

    Select districtSelect = new Select(driver.findElement(By.name(Constants.DDL_DISTRICT)));
    districtSelect.selectByIndex(districtIndex);

    if (logger.isDebugEnabled()) {

        logger.debug("getRefreshedBlockSelect(WebDriver, int) - selected district="
                + districtSelect.getAllSelectedOptions().toString()); //$NON-NLS-1$
    }//www .j a  va  2 s  .  c o  m

    waitForBlock(driver, getDistrictValueFromIndex(districtIndex), Constants.SELECT_0);
    Select blockSelect = new Select(driver.findElement(By.name(Constants.DDL_BLOCK)));

    return blockSelect;
}