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:com.amolik.scrapers.OdishaRationCardScraper.java

public static void processBlock(WebDriver driver, int districtIndex, int blockIndex, String blockValue,
        String blockName, ArrayList<OdishaRationCardBean> beanList) {
    // Select block based upon index

    Select blockSelect = getRefreshedBlockSelect(driver, districtIndex);
    blockSelect.selectByIndex(blockIndex);
    String districtName = districtsNameList.get(districtIndex);

    //      // Create new Directory if not exists
    //      String excelDestDirName = AmolikProperties.getProperty("odisha_ration.excelOutputDir")
    //            +System.getProperty("file.separator")
    //            +districtName;
    ////www. j a  va 2 s  .  c  o  m
    //      new File(excelDestDirName).mkdirs();
    //
    //      String excelDestFileName = excelDestDirName
    //            +Constants.BACK_SLASH+blockName+".xlsx";

    driver.findElement(By.name(Constants.BTN_SHOW)).click();
    waitForSubmit(driver, Constants.NO_DETAILS_FOUND, blockValue);

    int rowCount = driver.findElements(By.xpath("//table[@id='gvDist']/tbody/tr")).size();

    if (logger.isInfoEnabled()) {

        logger.info(districtIndex + "|" + districtName + "|" + blockIndex + "|" + blockName + "| recordCount="
                + (rowCount - 3)); //$NON-NLS-1$
    }

    // Remove during production
    //rowCount=7;

    if (rowCount > 2) {

        for (int i = 2; i < rowCount - 1; i++) {

            List<WebElement> columns = driver
                    .findElements(By.xpath("//table[@id='gvDist']/tbody/tr[" + (i + 1) + "]/td"));

            StringBuffer columnBuffer = new StringBuffer();

            // Temporary select max columns to process
            int columnToProcess = 5;
            columnToProcess = Math.min(columnToProcess, columns.size());

            OdishaRationCardBean bean = new OdishaRationCardBean();
            setBean(columns, columnToProcess, bean);
            beanList.add(bean);

        }
    }

}

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

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

    try {//from w ww.  j av  a 2s . com
        //            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 {/*w w  w.ja v a2  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.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();

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

From source file:com.babu.zadoqa.util.WaitTool.java

License:Open Source License

/**
  * Wait for an element to appear on the refreshed web-page.
  * And returns the first WebElement using the given method.
  */*from   w ww.  j a va2s .c  om*/
  * This method is to deal with dynamic pages.
  * 
  * Some sites I (Mark) have tested have required a page refresh to add additional elements to the DOM.  
  * Generally you (Chon) wouldn't need to do this in a typical AJAX scenario.
  * 
  * @param WebDriver   The driver object to use to perform this element search
  * @param locator   selector to find the element
  * @param int   The time in seconds to wait until returning a failure
  * 
  * @return WebElement   the first WebElement using the given method, or null(if the timeout is reached)
  * 
  * @author Mark Collin 
  */
public static WebElement waitForElementRefresh(WebDriver driver, final By by, int timeOutInSeconds) {
    WebElement element;
    try {
        driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS); //nullify implicitlyWait() 
        new WebDriverWait(driver, timeOutInSeconds) {
        }.until(new ExpectedCondition<Boolean>() {

            public Boolean apply(WebDriver driverObject) {
                driverObject.navigate().refresh(); //refresh the page ****************
                return isElementPresentAndDisplay(driverObject, by);
            }
        });
        element = driver.findElement(by);
        driver.manage().timeouts().implicitlyWait(DEFAULT_WAIT_4_PAGE, TimeUnit.SECONDS); //reset implicitlyWait
        return element; //return the element
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.ceiwc.compugain.setup.TestBase.java

/**
 * /*  www.j a  va 2 s.  c o m*/
 * @return : The language present in the HTML.
 */
public String getLanguagevalue(WebDriver driver) {
    String sflag = "";
    logger.info("message" + driver.findElement(By.xpath("//html[@class='ng-scope']")).getAttribute("lang"));
    if (driver.findElement(By.xpath("//html[@class='ng-scope']")).getAttribute("lang") != null) {
        sflag = driver.findElement(By.xpath("//html[@class='ng-scope']")).getAttribute("lang");
    } else {
        sflag = "en";
    }
    return sflag;
}

From source file:com.ceiwc.compugain.setup.TestBase.java

public void logout(WebDriver driver) {
    try {/*from  w w w . j av a  2  s .  c o m*/
        if (driver.findElement(By.xpath("//div[@id='account']/a/span")).isDisplayed()) {
            WebDriverWait driverwait = new WebDriverWait(driver, 60);
            driver.findElement(By.xpath("//div[@id='account']/a/span")).click();
            driverwait.until(
                    ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@class='glyphicons power']")));
            driver.findElement(By.xpath("//*[@class='glyphicons power']")).click();
            driverwait.until(
                    ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class='password']/input")));
        }
    } catch (Exception e) {
        logger.info("Logout button is not found!!!!!");
    }
}

From source file:com.cisco.dbds.utils.selenium.SeleniumUtilities.java

License:Open Source License

/**
 * Presence of element located./*from  ww  w.  j a v  a 2 s.  c o m*/
 * 
 * @param locator
 *            the locator
 * @return the function
 */
private static Function<WebDriver, WebElement> presenceOfElementLocated(final By locator) {
    return new Function<WebDriver, WebElement>() {
        @Override
        public WebElement apply(WebDriver driver) {
            return driver.findElement(locator);
        }
    };
}