Example usage for org.openqa.selenium WebDriver findElements

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

Introduction

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

Prototype

@Override
List<WebElement> findElements(By by);

Source Link

Document

Find all elements within the current page using the given mechanism.

Usage

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

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

    try {//from   w  w  w  .jav a  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 www  . j  a va  2s .c om*/
        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.babu.zadoqa.util.WaitTool.java

License:Open Source License

/**
  * Wait for the List<WebElement> to be present in the DOM, regardless of being displayed or not.
  * Returns all elements within the current page DOM. 
  * /*  w  w  w  . jav  a 2 s  .c o  m*/
  * @param WebDriver   The driver object to be used 
  * @param By   selector to find the element
  * @param int   The time in seconds to wait until returning a failure
  *
  * @return List<WebElement> all elements within the current page DOM, or null (if the timeout is reached)
  */
public static List<WebElement> waitForListElementsPresent(WebDriver driver, final By by, int timeOutInSeconds) {
    List<WebElement> elements;
    try {
        driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS); //nullify implicitlyWait() 

        WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
        wait.until((new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver driverObject) {
                return areElementsPresent(driverObject, by);
            }
        }));

        elements = driver.findElements(by);
        driver.manage().timeouts().implicitlyWait(DEFAULT_WAIT_4_PAGE, TimeUnit.SECONDS); //reset implicitlyWait
        return elements; //return the element   
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.cloudbees.workflow.ui.view.FailedJobTest.java

License:Open Source License

@Ignore("remove phantomjs: https://trello.com/c/JpUg8S5z/159-get-rid-of-phantomjs-webdriver")
@Test//from   w ww.  j a  v a  2s  . c o  m
public void test() throws Exception {
    WebDriver webdriver = getWebDriver();

    WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "Noddy Job");

    job.setDefinition(new CpsFlowDefinition("" + "node {" + "   stage ('Build'); " + "   sh ('blah'); " + "}"));

    QueueTaskFuture<WorkflowRun> build = job.scheduleBuild2(0);
    jenkinsRule.assertBuildStatus(Result.FAILURE, build.get());

    String jobUrl = getItemUrl(jenkinsRule.jenkins, job);
    webdriver.get(jobUrl);

    // Make sure the stage cell was marked as failed...
    List<WebElement> failedStageCells = webdriver
            .findElements(By.cssSelector(".stage-cell.FAILED .stage-wrapper"));
    Assert.assertEquals(1, failedStageCells.size());

    // Make the sure the stage-failed-popover widget was added to the cell
    WebElement failedStageCell = failedStageCells.get(0);
    List<WebElement> stageFailedPopovers = failedStageCell
            .findElements(By.cssSelector(".stage-failed-popover"));
    Assert.assertEquals(1, stageFailedPopovers.size());

    // Make sure that when we mouse over the failed stage cell we get a popup...
    moveMouseToElement(webdriver, failedStageCell);
    List<WebElement> popovers = waitForElementsAdded(webdriver, ".cbwf-popover");
    //        System.out.println(webdriver.getPageSource());
    Assert.assertTrue(popovers.size() > 0);

    // Make sure the popover has what we expect...
    Assert.assertEquals("Failed with the following error(s)\n" + "Shell Script script returned exit code 127\n"
            + "See stage logs for more detail.\n" + "Logs", popovers.get(0).getText().trim());

    // Make sure the popover is removed once we move off it
    //moveMouseOffElement(webdriver);
    //waitForElementsRemoved(webdriver, ".cbwf-popover");
}

From source file:com.cloudbees.workflow.ui.view.PausedJobTest.java

License:Open Source License

@Ignore("remove phantomjs: https://trello.com/c/JpUg8S5z/159-get-rid-of-phantomjs-webdriver")
@Test//w w  w.j  av a 2  s  .c o m
public void test() throws Exception {
    WebDriver webdriver = getWebDriver();

    WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "Noddy Job");

    job.setDefinition(new CpsFlowDefinition("" + "node {" + "   stage ('Build'); " + "   echo ('build'); "
            + "   input (message: 'Is the build okay?'); " + "}"));

    QueueTaskFuture<WorkflowRun> q = job.scheduleBuild2(0);
    WorkflowRun b = q.getStartCondition().get();
    CpsFlowExecution e = (CpsFlowExecution) b.getExecutionPromise().get();

    while (b.getAction(InputAction.class) == null) {
        e.waitForSuspension();
    }

    String jobUrl = getItemUrl(jenkinsRule.jenkins, job);
    webdriver.get(jobUrl);

    // Make sure the stage cell was marked as pending input...
    List<WebElement> pausedStageCells = webdriver
            .findElements(By.cssSelector(".stage-cell.PAUSED_PENDING_INPUT .stage-wrapper"));
    Assert.assertEquals(1, pausedStageCells.size());

    // Move over the paused build and check for the popup...
    moveMouseToElement(webdriver, pausedStageCells.get(0));
    List<WebElement> inputRequiredPopovers = waitForElementsAdded(webdriver,
            ".cbwf-popover .run-input-required");
    Assert.assertEquals(1, inputRequiredPopovers.size());

    // Check the popup content...
    WebElement inputRequiredPopover = inputRequiredPopovers.get(0);
    WebElement message = inputRequiredPopover.findElement(By.cssSelector(".message"));
    Assert.assertEquals("Is the build okay?", message.getText());

    // Click on the proceed button
    WebElement proceedBtn = inputRequiredPopover.findElement(By.cssSelector(".action.proceed"));
    //        clickOnElement(webdriver, proceedBtn);
    //
    //        // Wait for the build to complete successfully
    //        Util.waitForBuildCount(job, 1, Result.SUCCESS);
    //
    //        // Click on the proceed button and wait for the popup to disappear
    //        waitForElementsRemoved(webdriver, ".cbwf-popover .run-input-required");
}

From source file:com.cloudbees.workflow.ui.view.StagePopupsTest.java

License:Open Source License

@Ignore("remove phantomjs: https://trello.com/c/JpUg8S5z/159-get-rid-of-phantomjs-webdriver")
@Test//from   ww  w  .  ja v  a2 s .com
public void test() throws Exception {
    WebDriver webdriver = getWebDriver();

    WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "Noddy Job");

    job.setDefinition(new CpsFlowDefinition(
            "" + "node {" + "   stage ('Build'); " + "   sh ('ls'); " + "   sh ('blah'); " + "}"));

    QueueTaskFuture<WorkflowRun> build = job.scheduleBuild2(0);
    jenkinsRule.assertBuildStatus(Result.FAILURE, build.get());

    String jobUrl = getItemUrl(jenkinsRule.jenkins, job);
    webdriver.get(jobUrl);

    // Make sure the stage cell was marked as failed...
    List<WebElement> failedStageCells = webdriver
            .findElements(By.cssSelector(".stage-cell.FAILED .stage-wrapper"));
    Assert.assertEquals(1, failedStageCells.size());

    // Make the sure the stage-failed-popover widget was added to the cell
    WebElement failedStageCell = failedStageCells.get(0);
    List<WebElement> stageFailedPopovers = failedStageCell
            .findElements(By.cssSelector(".stage-failed-popover"));
    Assert.assertEquals(1, stageFailedPopovers.size());

    // Make sure that when we mouse over the failed stage cell we get a popup...
    moveMouseToElement(webdriver, failedStageCell);
    List<WebElement> popovers = waitForElementsAdded(webdriver, ".cbwf-popover");
    Assert.assertTrue(popovers.size() > 0);

    Assert.assertEquals("Failed with the following error(s)\n" + "Shell Script script returned exit code 127\n"
            + "See stage logs for more detail.\n" + "Logs", popovers.get(0).getText().trim());
}

From source file:com.cognifide.aet.sanity.functional.po.LoadedCondition.java

License:Apache License

@Nullable
@Override/*from  w ww  .ja v a 2 s  .  c om*/
public Integer apply(@Nullable WebDriver webDriver) {
    List<WebElement> elements = webDriver.findElements(selector);
    boolean tilesLoaded = !isStillLoading(elements) && alreadyLoaded > 0;
    return tilesLoaded ? elements.size() : null;
}

From source file:com.cognifide.qa.bb.provider.selenium.BobcatWait.java

License:Apache License

/**
 * This method checks if the element identified by the locator is present on the page
 * and returns immediately./*from   ww  w . j  a v a 2s  . c  o m*/
 *
 * @param locator Locator that identifies element on the page.
 * @return If true, then element is present on the page.
 */
public boolean checkPresenceWithNoTimeout(By locator) {
    WebDriver webDriver = webDriverProvider.get();
    webDriver.manage().timeouts().implicitlyWait(IMPLICITLY_WAIT_TIME, TimeUnit.MILLISECONDS);
    try {
        return !webDriver.findElements(locator).isEmpty();
    } finally {
        webDriver.manage().timeouts().implicitlyWait(defaultTimeout, TimeUnit.SECONDS);
    }
}

From source file:com.comcast.magicwand.drivers.AbstractPhoenixDriver.java

License:Apache License

/**
 * {@inheritDoc}/*from   w ww  . j  a  va2s .  c  om*/
 */
public List<WebElement> findElements(By arg0) {
    WebDriver driver = this.getDriver();
    List<WebElement> elements = null;

    if (null != driver) {
        elements = driver.findElements(arg0);
    }

    return elements;
}

From source file:com.common.ExpectedConditions.java

License:Apache License

/**
 * @see #findElement(By, WebDriver)/*from   w  w  w. j  a  v a 2  s  .  c o  m*/
 * @param driver WebDriver
 * @param by locator
 * @return List of WebElements found
 */
private static List<WebElement> findElements(By by, WebDriver driver) {
    try {
        return driver.findElements(by);
    } catch (WebDriverException e) {
        log.log(Level.WARNING, String.format("WebDriverException thrown by findElement(%s)", by), e);
        throw e;
    }
}