官术网_书友最值得收藏!

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\nSpan's Text"
  assertEquals("Div's Text\nSpan'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\nSpan's Text"
assertEquals("Div's Text\nSpan'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\nSpan'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
主站蜘蛛池模板: 进贤县| 海阳市| 绵竹市| 合川市| 滦南县| 新民市| 长岛县| 东安县| 嵊泗县| 苏州市| 闽侯县| 霍城县| 遵化市| 永吉县| 扎囊县| 温州市| 吐鲁番市| 界首市| 濮阳市| 南昌市| 随州市| 三亚市| 贡嘎县| 新邵县| 泰和县| 革吉县| 乐业县| 郴州市| 大邑县| 武清区| 永善县| 广安市| 辽源市| 高淳县| 沂水县| 淅川县| 泸水县| 怀仁县| 安图县| 甘泉县| 义马市|