Example usage for org.openqa.selenium WebElement getTagName

List of usage examples for org.openqa.selenium WebElement getTagName

Introduction

In this page you can find the example usage for org.openqa.selenium WebElement getTagName.

Prototype

String getTagName();

Source Link

Document

Get the tag name of this element.

Usage

From source file:org.cerberus.serviceEngine.impl.WebDriverService.java

License:Open Source License

@Override
public String getValueFromHTML(Session session, String locator) {
    WebElement webElement = this.getSeleniumElement(session, locator, false, false);
    String result = null;//from  www .j  a  va  2  s  . co  m

    if (webElement.getTagName().equalsIgnoreCase("select")) {
        if (webElement.getAttribute("disabled") == null || webElement.getAttribute("disabled").isEmpty()) {
            Select select = new Select(webElement);
            result = select.getFirstSelectedOption().getText();
        } else {
            result = webElement.getText();
            //result = "Unable to retrieve, element disabled ?";
        }
    } else if (webElement.getTagName().equalsIgnoreCase("option")
            || webElement.getTagName().equalsIgnoreCase("input")) {
        result = webElement.getAttribute("value");
    } else {
        result = webElement.getText();
    }
    /**
     * If return is empty, we search for hidden tags
     */
    if (StringUtil.isNullOrEmpty(result)) {
        String script = "return arguments[0].innerHTML";
        try {
            result = (String) ((JavascriptExecutor) session.getDriver()).executeScript(script, webElement);
        } catch (Exception e) {
            MyLogger.log(WebDriverService.class.getName(), Level.DEBUG,
                    "getValueFromHTML locator : '" + locator + "', exception : " + e.getMessage());
        }
    }

    return result;
}

From source file:org.fluentlenium.unit.GlobalSearch.java

License:Apache License

@Test
public void findByPosition() {
    String name = "cssStyle";
    WebElement webElement1 = mock(WebElement.class);
    when(webElement1.getTagName()).thenReturn("span");
    WebElement webElement2 = mock(WebElement.class);
    when(webElement2.getTagName()).thenReturn("a");
    List<WebElement> webElements = new ArrayList<WebElement>();
    webElements.add(webElement1);//from   w w  w .  j ava2s.  c o  m
    webElements.add(webElement2);
    when(searchContext.findElements(By.cssSelector("cssStyle"))).thenReturn(webElements);

    FluentWebElement fluentWebElement = search.find(name, 1);
    assertThat(fluentWebElement.getTagName()).isEqualTo("a");
}

From source file:org.fluentlenium.unit.GlobalSearch.java

License:Apache License

@Test
public void findFirstShouldReturnFirst() {
    String name = "cssStyle";
    WebElement webElement1 = mock(WebElement.class);
    when(webElement1.getTagName()).thenReturn("span");
    WebElement webElement2 = mock(WebElement.class);
    when(webElement2.getTagName()).thenReturn("a");
    List<WebElement> webElements = new ArrayList<WebElement>();
    webElements.add(webElement1);/* w ww. java2  s  .c o m*/
    webElements.add(webElement2);
    when(searchContext.findElements(By.cssSelector("cssStyle"))).thenReturn(webElements);

    FluentWebElement fluentWebElement = search.findFirst(name);
    assertThat(fluentWebElement.getTagName()).isEqualTo("span");
}

From source file:org.freespace.testingplatform.webdriver.helpers.TableCellHelper.java

License:Apache License

/**
 * <b>Most users should not need this constructor as the intended way to create a 
 * TabelCellHelper is to get a grid of them from a {@link TableHelper}.</b>
 * Create a TableCellHelper from the WebElement corresponding to an HTML table cell.  
 * @param cell A WebElement corresponding to the HTML TR or TD element.
 *///from  ww  w  .  j  a  v  a 2s .c  om
public TableCellHelper(WebElement cell) {
    _cell = cell;
    _isHeader = cell.getTagName().equalsIgnoreCase("th");
}

From source file:org.jboss.arquillian.graphene.ftest.page.extension.JQuerySelectorsPageExtensionTestCase.java

License:Open Source License

@Test
public void testJQuerySelectorCallingFindByDirectly() {
    ByJQuery headerBy = new ByJQuery(":header");
    WebElement headerElement = browser.findElement(headerBy);

    assertNotNull(headerElement);/* w w w .ja  v a2s.c  o m*/
    // unlike other drivers, SafariDriver returns tag names in upper case
    assertEquals("h1", headerElement.getTagName().toLowerCase());
}

From source file:org.jboss.test.selenium.support.ui.FocusRetriever.java

License:Open Source License

/**
 * Returns active (focused) element - if no element is focused (it means body element is active), null is returned
 *//* w  w w .j  a v  a  2 s. co  m*/
public static WebElement retrieveActiveElement() {
    WebElement element = JSInterfaceFactory.create(FocusRetriever.class).getActiveElement();
    if ("body".equals(element.getTagName())) {
        return null;
    }
    return element;
}

From source file:org.jspringbot.keyword.selenium.ElementFinder.java

License:Open Source License

private static WebElement filterElements(List<WebElement> elements, String tagName,
        Map<String, String> attributes) {
    if (CollectionUtils.isEmpty(elements)) {
        return null;
    }/*from   w ww. j av  a 2s.  co m*/

    if (StringUtils.isEmpty(tagName)) {
        return elements.iterator().next();
    }

    for (WebElement element : elements) {
        if (element.getTagName().equalsIgnoreCase(tagName)) {
            if (MapUtils.isEmpty(attributes)) {
                return element;
            } else {
                for (Map.Entry<String, String> entry : attributes.entrySet()) {
                    String value = element.getAttribute(entry.getKey());

                    if (StringUtils.equalsIgnoreCase(entry.getValue(), value)) {
                        return element;
                    }
                }
            }
        }
    }

    return null;
}

From source file:org.jspringbot.keyword.selenium.SeleniumHelper.java

License:Open Source License

private boolean isFormElement(WebElement element) {
    if (element == null) {
        return false;
    }//from   w  ww  .  ja  v a 2  s  .  com

    String tagName = element.getTagName().toLowerCase();
    return (tagName.equalsIgnoreCase("input") || tagName.equalsIgnoreCase("select")
            || tagName.equalsIgnoreCase("textarea") || tagName.equalsIgnoreCase("button"));
}

From source file:org.julianharty.accessibility.automation.KeyboardHelpers.java

License:Apache License

/**
 * Uses the tab key to navigate around a web page.
 *
 * Helps determine which elements are reachable with the tab key and
 * whether the first active element can be reached again (indicating we
 * can 'loop' around the tabable elements on the page.
 *
 * Any iFrames are visited recursively.// w ww  .j  a v a 2s . co  m
 * 
 * A sample call follows:
 * <code><br/>
public void testTabbingThroughGoogleSearchResults() throws InterruptedException { <br/>
   FirefoxDriver driver = new FirefoxDriver(); <br/>
   driver.get("http://www.google.com/search?q=cheese"); <br/>
   int maxTabsToEnter = 300; <br/>
   int tabs = KeyboardHelpers.tabThroughWebPage(driver, maxTabsToEnter);<br/>
   assertTrue("Expected at least 50 tabs, only needed " + tabs, tabs > 50);<br/>
 } </code>
 *
 * @param driver a WebDriver connection with the target page loaded.
 * @param maxTabsToEnter the maximum tabs we should need to visit all the
 * tabable elements. Consider providing a 2x or 3x the expected number,
 * particularly for complex, unknown content.  
 * @return the number of tabs issued if the method reached an element that
 * matched the first active element, else -1 if it failed to complete
 * within the specified number of tabs. 
 * @throws InterruptedException if the call to sleep fails. 
 */
public static int tabThroughWebPage(WebDriver driver, int maxTabsToEnter) throws InterruptedException {

    WebElement firstElement = driver.switchTo().activeElement();
    WebElement currentElement = firstElement;
    currentSize = firstElement.getSize();

    int tabsIssued = 0;
    int iFrame = 0;
    String currentTagName = "(not set)";
    try {
        while (tabsIssued < (maxTabsToEnter)) {
            Point currentLocation = currentElement.getLocation();
            logDetailsOfWebElement(currentElement, currentLocation, tabsIssued);
            currentTagName = currentElement.getTagName();

            /*
             * for iframes switch to the iframe and call ourself recursively. We
             * think it always starts from _top of the iframe. That call will
             * tab until it 'falls out' of the active elements in the iframe.
             * Body will then be returned, then we need to switch back to the
             * parent.
             * 
             * Note: use periods to separate nested frames.
             */

            if (currentTagName.equals("iframe")) {
                driver.switchTo().frame(iFrame++);
                // A simple calculation to limit tabs in a 'broken' iFrame for now.
                tabThroughWebPage(driver, maxTabsToEnter - tabsIssued);
                // Will the following skip over the 'body' of the iFrame?
                driver.switchTo().defaultContent();
                currentElement = driver.switchTo().activeElement();
            }

            String currentTitle = getTitleOfCurrentElement(driver, currentElement);

            // Here is one of the termination conditions, if we find one of our titles.
            if (currentTitle.contains(TAB_KEYWORD + 0)) {
                logTerminationCondition(
                        String.format("Title %s of element matches the value set", currentTitle),
                        currentElement, tabsIssued);
                return tabsIssued;
            }

            setWebElementAttributesAsAppropriate(driver, currentElement, tabsIssued, currentTagName);

            currentElement.sendKeys(Keys.TAB); // "\t" also works
            tabsIssued++;
            // TODO 2011Aug16 Don't sleep with IE driver, it's too slow
            // Thread.sleep(500L);

            String previousTagName = currentTagName;
            Point previousLocation = currentLocation;
            Dimension previousSize = currentSize;
            currentElement = driver.switchTo().activeElement();
            currentLocation = currentElement.getLocation();
            currentSize = currentElement.getSize();
            currentTagName = currentElement.getTagName();

            /* Loop termination is still imprecise. Typically the first element
             * is the body element, however in some GWT applications it's a div
             * element for reasons I don't yet fathom. 
             * TODO(jharty): improve the precision and reliability of the 
             * matching as we learn more about how to interact with elements
             * on the page. 
             */

            if (GeneralHelpers.locationMatches(currentLocation, previousLocation)
                    && GeneralHelpers.dimensionsAreEqual(currentSize, previousSize)
                    && currentTagName.equals(previousTagName) && !currentTagName.equals("body")) {
                logTerminationCondition(String.format(
                        "Bad news: Element %s seems to match %s after tabbing. Are NativeEvents working?",
                        currentTagName, previousTagName), currentElement, tabsIssued);
                // Tell the user to check native events are working
                return -1;
            }

            if (currentElement.equals(firstElement) && tabsIssued >= 3) {
                logTerminationCondition("Current element matches first element", currentElement, tabsIssued);
                return tabsIssued;
            }
        }
    } catch (WebDriverException wde) {
        String innerHTML = (String) ((JavascriptExecutor) driver)
                .executeScript("return arguments[0].innerHTML;", currentElement);
        LOG.warning(String.format("Current Tag %s, InnerHTML for problem element is %s", currentTagName,
                innerHTML));
        throw wde;
    }
    return -1;
}

From source file:org.julianharty.accessibility.automation.KeyboardHelpers.java

License:Apache License

/**
 * A helper method to log details of the web element from WebDriver.
 * @param element the element to report on
 * @param location the co-ordinates of the element
 * @param tabsIssued the number of tab keys issued so far
 *//*w  w  w  . jav  a  2 s  . c o m*/
private static void logDetailsOfWebElement(WebElement element, Point location, int tabsIssued) {
    // Probably want to print various attributes e.g. the link text
    LOG.info(String.format("%03d: Tag name %s WebElement %s name %s text %s value %s", tabsIssued,
            element.getTagName(), element.hashCode(), element.toString(), element.getText(),
            getValueFromWebdriverIfAvailable(element)));
    // RenderedWebElement rwe = (RenderedWebElement) element;
    LOG.info(String.format("[%03d] Location (%03d,%03d)", tabsIssued, location.x, location.y));
}