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

Understanding the text() methods

One very useful method in finding XPath is the text() method. When we need to supply some text at runtime, say for example, from an Excel file, then we can utilize the text() method in the following manner:

public class DynamicText {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\\SeleniumWD\\src\\main\\resources\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("http://www.google.com");
String variableData = "Google";
String dynamicXpath = "//*[text()='" + variableData + "']";
List<WebElement> elem =
driver.findElements(By.xpath(dynamicXpath));
System.out.println("no of elements: " + elem.size());

}
}

The program above prints
no of elements: 3