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

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
主站蜘蛛池模板: 金门县| 横山县| 铜陵市| 平阴县| 崇义县| 高雄县| 武定县| 长泰县| 渭源县| 桑日县| 含山县| 同心县| 仙游县| 海原县| 平陆县| 海丰县| 青川县| 正镶白旗| 内乡县| 湾仔区| 赣榆县| 凤凰县| 改则县| 商丘市| 珠海市| 昌宁县| 武川县| 福安市| 满洲里市| 昌图县| 宁城县| 枣庄市| 肇东市| 北票市| 永善县| 南漳县| 嵊州市| 宁晋县| 临洮县| 澄迈县| 宝山区|