Selenium WebDriver 3 Practical Guide
上QQ阅读APP看书,第一时间看更新

The getText() method

The getText method can be called from all the WebElements. It will return visible text if the element contains any text on it, otherwise it will return nothing.  The API syntax for the getText() method is as follows:

java.lang.String getText()

There is no input parameter for the preceding method, but it returns the visible innerText string of the WebElement if anything is available, otherwise it will return an empty string.

The following is the code to get the text present on the Site notice element present on the example application Homepage:

@Test
public void elementGetTextExample() {
WebElement siteNotice = driver.findElement(By
.className("global-site-notice"));

System.out.println("Complete text is: "
+ siteNotice.getText());
}

The preceding code uses the getText() method to fetch the text present on the Site notice element, which returns the following:

Complete text is: This is a demo store. Any orders placed through this store will not be honored or fulfilled.