Checking an element's text

While testing a web application, we need to verify that elements are displaying the correct values or text on the page. Selenium WebDriver's WebElement interface provides methods to retrieve and verify text from an element. Sometimes we need to retrieve text or values from an element into a variable at runtime and later use it at some other place in the test flow.

In this recipe, we will retrieve and verify text from an element using the getText() method of the WebElement interface.

How to do it...

Here, we will create a test that finds an element and then retrieves text from the element in a string variable. We will verify the contents of this string for correctness using the following code:

@Test
public void testElementText() {
  // Get the message Element
  WebElement message = driver.findElement(By.id("message"));

  // Get the message elements text
  String messageText = message.getText();

  // Verify message element's text displays "Click on me and my
  // color will change"
  assertEquals("Click on me and my color will change",
    messageText);

  // Get the area Element
  WebElement area = driver.findElement(By.id("area"));

  // Verify area element's text displays "Div's Text
Span's Text"
  assertEquals("Div's Text
Span's Text", area.getText());
}

How it works...

The getText() method of the WebElement interface returns the visible innerText of the element, including sub-elements, without any leading or trailing whitespace.

If the element has child elements, the value of the innerText attribute of the child elements will also be returned along with the parent element. In the following example, we have a <span> element within a <div> element. While we are retrieving innerText from the <div> element it also appends innerText of the <span> element:

// Get the area Element
WebElement area = driver.findElement(By.id("area"));

// Verify element's text displays "Div's Text
Span's Text"
assertEquals("Div's Text
Span's Text",area.getText());

There's more...

The WebElement.getText() method does not work on hidden or invisible elements. Retrieval of text from such elements is possible through the getAttribute() method using the innerText or textContent attributes:

assertEquals("Div's Text
Span's Text",area.getAttribute("innerText"));

The innerText attribute is not supported in Firefox and the textContent attribute is not supported in Internet Explorer.

See also

  • The Checking an element's attribute and CSS values recipe
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.196.171