Java Code Examples for org.openqa.selenium.WebDriver#findElements()

The following examples show how to use org.openqa.selenium.WebDriver#findElements() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RealHtmlElementLocator.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
public static List<WebElement> findElements( UiElement uiElement, String xpathSuffix, boolean verbose ) {

        AbstractRealBrowserDriver browserDriver = (AbstractRealBrowserDriver) uiElement.getUiDriver();
        WebDriver webDriver = (WebDriver) browserDriver.getInternalObject(InternalObjectsEnum.WebDriver.name());
        HtmlNavigator.getInstance().navigateToFrame(webDriver, uiElement);

        String xpath = uiElement.getElementProperties()
                                .getInternalProperty(HtmlElementLocatorBuilder.PROPERTY_ELEMENT_LOCATOR);

        String css = uiElement.getElementProperty("_css");

        if (xpathSuffix != null) {
            xpath += xpathSuffix;
        }

        if (!StringUtils.isNullOrEmpty(css)) {
            return webDriver.findElements(By.cssSelector(css));
        } else {
            return webDriver.findElements(By.xpath(xpath));
        }

    }
 
Example 2
Source File: ExtJS22Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Test
public void core_templates() throws Exception {
    final WebDriver driver = getPage("core", "templates");
    final List<WebElement> buttons = driver.findElements(By.xpath("//button"));
    final List<WebElement> divs = driver.findElements(By.xpath("//div[@class='x-panel-body']"));
    assertEquals(2, buttons.size());
    assertEquals(2, divs.size());
    assertEquals("Apply the template to see results here", divs.get(0).getText());
    assertEquals("Apply the template to see results here", divs.get(1).getText());

    buttons.get(0).click();
    assertEquals("Name: Jack Slocum\n" + "Company: Ext JS, LLC\n"
        + "Location: Cleveland, Ohio", divs.get(0).getText());
    assertEquals("Apply the template to see results here", divs.get(1).getText());

    buttons.get(1).click();
    assertEquals("Name: Jack Slocum\n" + "Company: Ext JS, LLC\n"
        + "Location: Cleveland, Ohio", divs.get(0).getText());
    assertEquals("Name: Jack Slocum\n" + "Company: Ext JS, LLC\n"
        + "Location: Cleveland, Ohio\n"
        + "Kids:\n" + "1. Jack Slocum's kid - Sara Grace\n"
        + "2. Jack Slocum's kid - Zachary", divs.get(1).getText());
}
 
Example 3
Source File: AXE.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 6 votes vote down vote up
/**
 * Recursively find frames and inject a script into them.
 *
 * @param driver An initialized WebDriver
 * @param script Script to inject
 * @param parents A list of all toplevel frames
 */
private static void injectIntoFrames(final WebDriver driver, final String script, final ArrayList<WebElement> parents) {
    final JavascriptExecutor js = (JavascriptExecutor) driver;
    final List<WebElement> frames = driver.findElements(By.tagName("iframe"));

    frames.stream().map((frame) -> {
        driver.switchTo().defaultContent();
        if (parents != null) {
            parents.stream().forEach((parent) -> {
                driver.switchTo().frame(parent);
            });
        }
        driver.switchTo().frame(frame);
        return frame;
    }).forEach((frame) -> {
        js.executeScript(script);
        if (parents != null) {
            ArrayList<WebElement> localParents = (ArrayList<WebElement>) parents.clone();
            localParents.add(frame);

            injectIntoFrames(driver, script, localParents);
        }
    });
}
 
Example 4
Source File: ExpectedConditions.java    From selenium with Apache License 2.0 6 votes vote down vote up
/**
 * An expectation for checking number of WebElements with given locator being less than defined
 * number
 *
 * @param locator used to find the element
 * @param number  used to define maximum number of elements
 * @return Boolean true when size of elements list is less than defined
 */
public static ExpectedCondition<List<WebElement>> numberOfElementsToBeLessThan(final By locator,
                                                                               final Integer number) {
  return new ExpectedCondition<List<WebElement>>() {
    private Integer currentNumber = 0;

    @Override
    public List<WebElement> apply(WebDriver webDriver) {
      List<WebElement> elements = webDriver.findElements(locator);
      currentNumber = elements.size();
      return currentNumber < number ? elements : null;
    }

    @Override
    public String toString() {
      return String.format("number of elements found by %s to be less than \"%s\". Current number: \"%s\"",
                           locator, number, currentNumber);
    }
  };
}
 
Example 5
Source File: ClickOn.java    From NetDiscovery with Apache License 2.0 6 votes vote down vote up
@Override
public SeleniumAction perform(WebDriver driver) {

    List<WebElement> elements = driver.findElements(by);
    if (elements != null) {
        for (WebElement currentElement : elements) {
            if (currentElement.isEnabled() &&
                    currentElement.isDisplayed() &&
                    currentElement.getSize().getHeight() > 0 &&
                    currentElement.getSize().getWidth() > 0) {

                currentElement.click();

                return this;
            }
        }
    }
    return this;
}
 
Example 6
Source File: NoraUiExpectedConditions.java    From NoraUi with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * An expectation for checking that nb elements that match (or less) the locator are present on the web page.
 *
 * @param locator
 *            Locator of elements
 * @param nb
 *            Expected number of elements
 * @return the list of WebElements once they are located
 */
public static ExpectedCondition<List<WebElement>> presenceOfMaximumElementsLocatedBy(final By locator, final int nb) {
    return (WebDriver driver) -> {
        try {
            final List<WebElement> elements = driver.findElements(locator);
            return elements.size() <= nb ? elements : null;
        } catch (final Exception e) {
            return null;
        }
    };
}
 
Example 7
Source File: ExtJS22Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Test
public void core_spotlight() throws Exception {
    final WebDriver driver = getPage("core", "spotlight");
    final List<WebElement> buttons = driver.findElements(By.xpath("//button"));
    assertEquals(4, buttons.size());
    assertEquals("Start", buttons.get(0).getText());
    assertEquals("Next Panel", buttons.get(1).getText());
    assertEquals("Next Panel", buttons.get(2).getText());
    assertEquals("Done", buttons.get(3).getText());

    assertTrue(core_spotlight_isDisabled(buttons.get(1)));
    assertTrue(core_spotlight_isDisabled(buttons.get(2)));
    assertTrue(core_spotlight_isDisabled(buttons.get(3)));

    buttons.get(0).click();
    Thread.sleep(200);
    assertFalse(core_spotlight_isDisabled(buttons.get(1)));
    assertTrue(core_spotlight_isDisabled(buttons.get(2)));
    assertTrue(core_spotlight_isDisabled(buttons.get(3)));

    buttons.get(1).click();
    Thread.sleep(200);
    assertTrue(core_spotlight_isDisabled(buttons.get(1)));
    assertFalse(core_spotlight_isDisabled(buttons.get(2)));
    assertTrue(core_spotlight_isDisabled(buttons.get(3)));

    buttons.get(2).click();
    Thread.sleep(200);
    assertTrue(core_spotlight_isDisabled(buttons.get(1)));
    assertTrue(core_spotlight_isDisabled(buttons.get(2)));
    assertFalse(core_spotlight_isDisabled(buttons.get(3)));

    buttons.get(3).click();
    Thread.sleep(200);
    assertTrue(core_spotlight_isDisabled(buttons.get(1)));
    assertTrue(core_spotlight_isDisabled(buttons.get(2)));
    assertTrue(core_spotlight_isDisabled(buttons.get(3)));
}
 
Example 8
Source File: CoreTestSuite.java    From selenium with Apache License 2.0 5 votes vote down vote up
public Results run(WebDriver driver, Selenium selenium, URL baseUrl) {
  if (!url.equals(driver.getCurrentUrl())) {
    driver.get(url);
  }

  List<WebElement> allTables = driver.findElements(By.id("suiteTable"));
  if (allTables.isEmpty()) {
    throw new SeleniumException("Unable to locate suite table: " + url);
  }

  //noinspection unchecked
  List<String> allTestUrls = (List<String>) ((JavascriptExecutor) driver).executeScript(
    "var toReturn = [];\n" +
    "for (var i = 0; i < arguments[0].rows.length; i++) {\n" +
    "  if (arguments[0].rows[i].cells.length == 0) {\n" +
    "    continue;\n" +
    "  }\n" +
    "  var cell = arguments[0].rows[i].cells[0];\n" +
    "  if (!cell) { continue; }\n" +
    "  var allLinks = cell.getElementsByTagName('a');\n" +
    "  if (allLinks.length > 0) {\n" +
    "    toReturn.push(allLinks[0].href);\n" +
    "    arguments[0].rows[i].className += 'insert-test-result';\n" +
    "  }\n" +
    "}\n" +
    "return toReturn;\n",
    allTables.get(0));

  String rawSuite = (String) ((JavascriptExecutor) driver).executeScript(
    "return arguments[0].outerHTML;",
    allTables.get(0));

  Results results = new Results(rawSuite);

  for (String testUrl : allTestUrls) {
    new CoreTestCase(testUrl).run(results, driver, selenium, baseUrl);
  }

  return results;
}
 
Example 9
Source File: Prototype150rc1Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean testFinished(final WebDriver driver) {
    final List<WebElement> status = driver.findElements(By.cssSelector("div#logsummary"));
    for (WebElement webElement : status) {
        if (!webElement.getText().contains("errors")) {
            return false;
        }
    }
    return true;
}
 
Example 10
Source File: GetAllFields.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
protected String[] handleSeleneseCommand(WebDriver driver, String locator, String value) {
  List<WebElement> allInputs = driver.findElements(By.xpath("//input"));
  List<String> ids = new ArrayList<>();

  for (WebElement input : allInputs) {
    String type = input.getAttribute("type").toLowerCase();
    if ("text".equals(type))
      ids.add(input.getAttribute("id"));
  }

  return ids.toArray(new String[ids.size()]);
}
 
Example 11
Source File: DeleteTableRowByNumberIT.java    From bromium with MIT License 5 votes vote down vote up
private static WebElement getElement(WebDriver driver) {
    List<WebElement> elements = driver.findElements(By.tagName("li"));

    WebElement webElement = elements.get(2);

    return webElement
            .findElement(By.className("delete-button"));
}
 
Example 12
Source File: AdfComponent.java    From adf-selenium with Apache License 2.0 5 votes vote down vote up
protected AdfComponent(WebDriver driver, String clientid) {
    this.driver = driver;
    this.clientid = clientid;
    final List<WebElement> elems = driver.findElements(By.id(clientid));
    // some components do not have element (like dynamic declarative component)
    // TODO: why not lazy resolving in getElement?
    this.element = (elems != null && elems.size() == 1) ? elems.get(0) : null;
}
 
Example 13
Source File: GetAllLinks.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
protected String[] handleSeleneseCommand(WebDriver driver, String locator, String value) {
  List<WebElement> allLinks = driver.findElements(By.xpath("//a"));
  List<String> links = new ArrayList<>();
  for (WebElement link : allLinks) {
    String id = link.getAttribute("id");
    links.add(id == null ? "" : id);
  }

  return links.toArray(new String[links.size()]);

}
 
Example 14
Source File: XPathFinder.java    From selenium with Apache License 2.0 4 votes vote down vote up
@Override
protected Collection<WebElement> extractFrom(WebDriver context) {
  return context.findElements(By.xpath(xpath));
}
 
Example 15
Source File: WebDriverUtils.java    From rice with Educational Community License v2.0 4 votes vote down vote up
public static void highlightElement(WebDriver webDriver, By by) {
    List<WebElement> elements = webDriver.findElements(by);
    for (WebElement element : elements) {
        WebDriverUtils.highlightElement(webDriver, element);
    }
}
 
Example 16
Source File: HiddenHtmlElementLocator.java    From ats-framework with Apache License 2.0 4 votes vote down vote up
public static HtmlUnitWebElement findElement( UiElement uiElement, String xpathSuffix, boolean verbose ) {

        HiddenBrowserDriver browserDriver = (HiddenBrowserDriver) uiElement.getUiDriver();
        WebDriver webDriver = (WebDriver) browserDriver.getInternalObject(InternalObjectsEnum.WebDriver.name());
        HtmlNavigator.getInstance().navigateToFrame(webDriver, uiElement);

        String xpath = uiElement.getElementProperties()
                                .getInternalProperty(HtmlElementLocatorBuilder.PROPERTY_ELEMENT_LOCATOR);

        String css = uiElement.getElementProperty("_css");

        if (xpathSuffix != null) {
            xpath += xpathSuffix;
        }

        List<WebElement> elements = null;

        if (!StringUtils.isNullOrEmpty(css)) {
            elements = webDriver.findElements(By.cssSelector(css));
        } else {
            elements = webDriver.findElements(By.xpath(xpath));
        }

        if (elements.size() == 0) {

            throw new ElementNotFoundException(uiElement.toString() + " not found.");
        } else if (elements.size() > 1) {
            if (verbose) {

                log.warn("More than one HTML elements were found having properties " + uiElement.toString()
                         + ".Only the first HTML element will be used.");

            }
        }
        HtmlUnitWebElement element = (HtmlUnitWebElement) elements.get(0);
        if (verbose) {

            log.info("Found element: " + element.toString());
        }
        return element;
    }
 
Example 17
Source File: Utilities.java    From NoraUi with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Check if element present and get first one.
 *
 * @param element
 *            is {link org.openqa.selenium.By} find in page.
 * @return first {link org.openqa.selenium.WebElement} finded present element.
 */
public static WebElement isElementPresentAndGetFirstOne(By element) {

    final WebDriver webDriver = Context.getDriver();

    webDriver.manage().timeouts().implicitlyWait(DriverFactory.IMPLICIT_WAIT * 2, TimeUnit.MICROSECONDS);

    final List<WebElement> foundElements = webDriver.findElements(element);
    final boolean exists = !foundElements.isEmpty();

    webDriver.manage().timeouts().implicitlyWait(DriverFactory.IMPLICIT_WAIT, TimeUnit.MICROSECONDS);

    if (exists) {
        return foundElements.get(0);
    } else {
        return null;
    }

}
 
Example 18
Source File: HTMLLauncher.java    From selenium with Apache License 2.0 4 votes vote down vote up
/**
 * Launches a single HTML Selenium test suite.
 *
 * @param browser - the browserString ("*firefox", "*iexplore" or an executable path)
 * @param startURL - the start URL for the browser
 * @param suiteURL - the relative URL to the HTML suite
 * @param outputFile - The file to which we'll output the HTML results
 * @param timeoutInSeconds - the amount of time (in seconds) to wait for the browser to finish
 * @return PASS or FAIL
 * @throws IOException if we can't write the output file
 */
public String runHTMLSuite(
  String browser,
  String startURL,
  String suiteURL,
  File outputFile,
  long timeoutInSeconds,
  String userExtensions) throws IOException {
  File parent = outputFile.getParentFile();
  if (parent != null && !parent.exists()) {
    parent.mkdirs();
  }
  if (outputFile.exists() && !outputFile.canWrite()) {
    throw new IOException("Can't write to outputFile: " + outputFile.getAbsolutePath());
  }
  long timeoutInMs = 1000L * timeoutInSeconds;
  if (timeoutInMs < 0) {
    log.warning("Looks like the timeout overflowed, so resetting it to the maximum.");
    timeoutInMs = Long.MAX_VALUE;
  }

  WebDriver driver = null;
  try {
    driver = createDriver(browser);
    URL suiteUrl = determineSuiteUrl(startURL, suiteURL);

    driver.get(suiteUrl.toString());
    Selenium selenium = new WebDriverBackedSelenium(driver, startURL);
    selenium.setTimeout(String.valueOf(timeoutInMs));
    if (userExtensions != null) {
      selenium.setExtensionJs(userExtensions);
    }
    List<WebElement> allTables = driver.findElements(By.id("suiteTable"));
    if (allTables.isEmpty()) {
      throw new RuntimeException("Unable to find suite table: " + driver.getPageSource());
    }
    Results results = new CoreTestSuite(suiteUrl.toString()).run(driver, selenium, new URL(startURL));

    HTMLTestResults htmlResults = results.toSuiteResult();
    try (Writer writer = Files.newBufferedWriter(outputFile.toPath())) {
      htmlResults.write(writer);
    }

    return results.isSuccessful() ? "PASSED" : "FAILED";
  } finally {
    if (server != null) {
      try {
        server.stop();
      } catch (Exception e) {
        // Nothing sane to do. Log the error and carry on
        log.log(Level.INFO, "Exception shutting down server. You may ignore this.", e);
      }
    }

    if (driver != null) {
      driver.quit();
    }
  }
}
 
Example 19
Source File: CustomerSignup.java    From java-maven-selenium with MIT License 4 votes vote down vote up
@Step("See items available for purchase.")
public void seeItemsAvailableForPurchase() {
    WebDriver webDriver = Driver.webDriver;
    List<WebElement> products = webDriver.findElements(By.className("product"));
    assertThat(products.size(), is(not(0)));
}
 
Example 20
Source File: ExpectSteps.java    From NoraUi with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * @deprecated As of release 4.1, replaced by {@link com.github.noraui.selenium.NoraUiExpectedConditions#presenceOfNbElementsLocatedBy(By locator, int nb)}
 *             An expectation for checking that nb elements that match the locator are present on the web page.
 * @param locator
 *            Locator of elements
 * @param nb
 *            Expected number of elements
 * @return the list of WebElements once they are located
 */
@Deprecated
public static ExpectedCondition<List<WebElement>> presenceOfNbElementsLocatedBy(final By locator, final int nb) {
    return (WebDriver driver) -> {
        final List<WebElement> elements = driver.findElements(locator);
        return elements.size() == nb ? elements : null;
    };
}