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

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
主站蜘蛛池模板: 景谷| 黔东| 乌兰浩特市| 塔河县| 铅山县| 祁门县| 浠水县| 扎鲁特旗| 宁晋县| 江门市| 洛宁县| 辛集市| 泌阳县| 双江| 溧水县| 玛沁县| 奉节县| 江陵县| 镇沅| 桦甸市| 宁远县| 定兴县| 秭归县| 三台县| 鄂托克旗| 明水县| 闽清县| 兴业县| 镇安县| 普兰店市| 仙游县| 勃利县| 潞城市| 介休市| 土默特左旗| 新密市| 奉化市| 华安县| 古丈县| 巢湖市| 原阳县|