Example usage for org.openqa.selenium WebDriver get

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

Introduction

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

Prototype

void get(String url);

Source Link

Document

Load a new web page in the current browser window.

Usage

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 ;/*  ww w . j  a 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.alfonsogalvanmadera.robot.Leer.java

/**
 * @param args the command line arguments
 */// w  w w . j  a  v a  2s. co  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

/**
 * Authenticates this client to LWA./*from w  w  w  .j  a v  a2 s  .  co 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.amolik.scrapers.OdishaRationCardScraper.java

public static void main(String[] args) throws Exception {
    ;//w  ww  .java 2  s  .  com

    // The Firefox driver supports javascript 
    WebDriver driver = new FirefoxDriver();

    driver.get(AmolikProperties.getProperty("odisha_ration.startUrl"));
    baseDir = AmolikProperties.getProperty("odisha_ration.baseDir");
    excelTemplateFileName = AmolikProperties.getProperty("odisha_ration.excelTemplateFileName");
    excelFileExtension = AmolikProperties.getProperty("odisha_ration.excelExtension");

    if (logger.isInfoEnabled()) {

        logger.info("startUrl=" + AmolikProperties.getProperty("odisha_ration.startUrl"));
    }

    processAllDistricts(driver);

    if (driver != null) {

        driver.close();

    }
}

From source file:com.arifnazarpurwandaru.selenium.MainFrame.java

private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed

    try {/*from www  .ja  va  2  s.  c om*/
        //            MarionetteDriverManager.getInstance().setup();
        System.out.println("Mulai Pencarian...");
        //      Runtime.getRuntime().exec("TASKKILL /F /IM Firefox.exe");
        //      Runtime.getRuntime().exec("TASKKILL /F /IM iexplore.exe");
        //      Runtime.getRuntime().exec("TASKKILL /F /IM iexplore.exe");

        WebDriver driver = null;
        String kereta = ((ComboItem) comboKereta.getSelectedItem()).getValue();

        //use proxy
        if (radioUseProxy.isSelected()) {
            String proxyHost = hostProxy.getText() + ":" + portProxy.getText();
            Proxy proxy = new Proxy();
            proxy.setHttpProxy(proxyHost);
            proxy.setSslProxy(proxyHost);
            proxy.setFtpProxy(proxyHost);
            proxy.setSocksUsername(usernameProxy.getText());
            proxy.setSocksPassword(new String(passwordProxy.getPassword()));

            DesiredCapabilities cap = new DesiredCapabilities();
            cap.setCapability(CapabilityType.PROXY, proxy);

            driver = new ChromeDriver(cap);
        } else {

            //                    driver = new MarionetteDriver();
            driver = new ChromeDriver();
        }
        //       hmin = Integer.valueOf(args[0]).intValue();
        ComboItem link = (ComboItem) comboLink.getSelectedItem();
        driver.get(link.getValue());
        List<WebElement> list = null;
        int counter = 1;
        boolean keeploop = true;
        while (/**list==null || list.size() == 0**/
        keeploop) {

            try {
                Select selectTgl = new Select(driver.findElement(By.name("tanggal")));
                selectTgl.selectByIndex(comboTanggal.getSelectedIndex());

                ComboItem stFrom = (ComboItem) comboStBerangkat.getSelectedItem();
                Select selectFrom = new Select(driver.findElement(By.name("origination")));
                selectFrom.selectByValue(stFrom.getValue());

                ComboItem stTo = (ComboItem) comboStTujuan.getSelectedItem();
                Select selectTo = new Select(driver.findElement(By.name("destination")));
                selectTo.selectByValue(stTo.getValue());

                Select selectAdult = new Select(driver.findElement(By.name("adult")));
                selectAdult.selectByValue("1");

                WebElement element = driver.findElement(By.name("Submit"));
                element.click();
                //          Thread.sleep(1000);
                //tunggu sampe page ready, nandainnya kalo element div dengan css class "itReservationContent" muncul
                WebElement elementForWait = (new WebDriverWait(driver, 1)).until(
                        ExpectedConditions.visibilityOfElementLocated(By.className("itReservationContent")));
                //end wait

                list = driver.findElements(By.className("itButton"));
                if (list != null && list.size() > 0) {
                    List<WebElement> listForm = driver.findElements(By.tagName("form"));
                    for (WebElement form : listForm) {
                        List<WebElement> listInput = form.findElements(By.tagName("input"));
                        for (WebElement input : listInput) {
                            if (input.getAttribute("value").equalsIgnoreCase(kereta)) {
                                WebElement btn = form.findElement(By.className("itButton"));
                                btn.click();
                                System.out.println("========================>KLIK BOOKING");
                                keeploop = false;
                                throw new KlikException("BerhasilKlik");
                            }
                        }
                    }
                }
                System.out.println("==========================> looping ke: " + counter);
                counter++;
            } catch (KlikException ke) {
                System.out.println("================> Masuk Klik Exception");
                keeploop = false;
                break;
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("===================> Reconecting..." + link.getValue());
                driver.get(link.getValue());
            }
        }

        //       System.out.println("ada keretaaaaaa: "+list.size());
        List<WebElement> listInput = driver.findElements(By.tagName("input"));
        for (WebElement input : listInput) {
            if (input.getAttribute("type").equals("checkbox")) {
                input.click();
                break;
            }
        }
        WebElement lanjut = driver.findElement(By.cssSelector("input[type='submit'][name='booking']"));
        lanjut.click();

        //Ngisi Tikete 
        //Nunggu disit
        //tunggu sampe page ready, nandainnya kalo element div dengan css class "txt_first_name_adult_1" muncul
        WebElement elementForWait = (new WebDriverWait(driver, 3))
                .until(ExpectedConditions.visibilityOfElementLocated(By.id("txt_first_name_adult_1")));
        //end wait
        WebElement namaPenumpang = driver.findElement(By.id("txt_first_name_adult_1"));
        WebElement ktp = driver.findElement(By.id("txt_passport_1"));

        WebElement contactName = driver.findElement(By.id("txt_contact_first_name"));
        WebElement contactEmail = driver.findElement(By.id("txt_contact_email"));
        WebElement contactPhone = driver.findElement(By.id("txt_contact_phone"));
        WebElement contactAddress = driver.findElement(By.id("txt_contact_home_address"));

        namaPenumpang.sendKeys(txtNamaPenumpang.getText());
        ktp.sendKeys(txtNoKTP.getText());
        contactName.sendKeys(txtNamaPenumpang.getText());
        contactEmail.sendKeys(txtEmail.getText());
        contactPhone.sendKeys(txtNoTelp.getText());
        contactAddress.sendKeys(txtAlamat.getText());

        playSound();

        JOptionPane.showMessageDialog(rootPane,
                "Booking sudah tersedia, Silakan inputkan Captcha!! Dan lanjutkan secara manual", "Informasi",
                JOptionPane.INFORMATION_MESSAGE);
        this.setAlwaysOnTop(true);

        System.out.println("DONE");
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.arifnazarpurwandaru.selenium.MainFrame.java

private void btnSearchBiasaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchBiasaActionPerformed

    try {//from   w w  w .j  a  v  a 2 s  .c o m
        Runtime.getRuntime().exec("TASKKILL /F /IM Firefox.exe");
        Runtime.getRuntime().exec("TASKKILL /F /IM iexplore.exe");

        WebDriver driver = null;

        //use proxy
        if (radioUseProxy.isSelected()) {
            String proxyHost = hostProxy.getText() + ":" + portProxy.getText();
            Proxy proxy = new Proxy();
            proxy.setHttpProxy(proxyHost);
            proxy.setSslProxy(proxyHost);
            proxy.setFtpProxy(proxyHost);
            proxy.setSocksUsername(usernameProxy.getText());
            proxy.setSocksPassword(new String(passwordProxy.getPassword()));

            DesiredCapabilities cap = new DesiredCapabilities();
            cap.setCapability(CapabilityType.PROXY, proxy);

            driver = new ChromeDriver(cap);
        } else {
            driver = new ChromeDriver();
        }

        ComboItem link = (ComboItem) comboLink.getSelectedItem();
        driver.get(link.getValue());
        List<WebElement> list = null;
        int counter = 1;

        while (list == null || list.size() == 0) {

            try {
                Select selectTgl = new Select(driver.findElement(By.name("tanggal")));
                selectTgl.selectByIndex(comboTanggalBiasa.getSelectedIndex());

                ComboItem ck = (ComboItem) comboStBerangkatBiasa.getSelectedItem();
                Select selectFrom = new Select(driver.findElement(By.name("origination")));
                selectFrom.selectByValue(ck.getValue());

                ComboItem ct = (ComboItem) comboStTujuanBiasa.getSelectedItem();
                Select selectTo = new Select(driver.findElement(By.name("destination")));
                selectTo.selectByValue(ct.getValue());

                Select selectAdult = new Select(driver.findElement(By.name("adult")));
                selectAdult.selectByValue("1");

                WebElement element = driver.findElement(By.name("Submit"));
                element.click();

                //tunggu sampe page ready, nandainnya kalo element div dengan css class "itReservationContent" muncul
                WebElement elementForWait = (new WebDriverWait(driver, 1)).until(
                        ExpectedConditions.visibilityOfElementLocated(By.className("itReservationContent")));
                //end wait

                list = driver.findElements(By.className("itButton"));
                System.out.println("==========================> looping ke: " + counter);
                counter++;
            } catch (Exception e) {
                System.out.println("===================> Reconecting..." + link.getValue());
                driver.get(link.getValue());
            }
        }
        System.out.println("ada keretaaaaaa: " + list.size());
        System.out.println("DONE");
    } catch (Exception e) {
        e.printStackTrace();
    }

}

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 ww w .  j a  va  2  s.c  om*/
        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.AddTochart.java

public static void main(String[] args) {

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

    driver.findElement(By.xpath(".//*[@id='homefeatured']/li[1]/div/div[2]/div[2]/a[1]/span")).click();
    driver.findElement(By.xpath(".//*[@id='layer_cart']/div[1]/div[2]/div[4]/a/span")).click();

    if (driver.switchTo().alert() != null) {
        Alert alert = driver.switchTo().alert();
        String alertText = alert.getText();
        alert.dismiss(); // alert.accept();

    }//from   ww  w. ja  v a2  s .c  o  m

}

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:/*  ww  w.  j  a v a  2 s  .  c  om*/
    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();

}

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

public static void main(String[] args) {

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

    //this codes is for automated test "sort product" in page "DRESSES" 
    driver.findElement(By.xpath(".//*[@id='block_top_menu']/ul/li[2]/a")).click();
    driver.findElement(By.xpath(".//*[@id='selectProductSort']")).sendKeys("price:asc");
    driver.navigate().back();/* www  .  j a v a  2  s  .co m*/
    driver.findElement(By.xpath(".//*[@id='block_top_menu']/ul/li[2]/a")).click();
    driver.findElement(By.xpath(".//*[@id='selectProductSort']")).sendKeys("price:desc");
    driver.navigate().back();
    driver.findElement(By.xpath(".//*[@id='block_top_menu']/ul/li[2]/a")).click();
    driver.findElement(By.xpath(".//*[@id='selectProductSort']")).sendKeys("name:asc");
    driver.navigate().back();
    driver.findElement(By.xpath(".//*[@id='block_top_menu']/ul/li[2]/a")).click();
    driver.findElement(By.xpath(".//*[@id='selectProductSort']")).sendKeys("name:desc");
    driver.quit();
}