用 Selenium 2 在页面中查找文本
我们可以用 Selenium webdriver 在页面上查找文本。首先,我们应该借助定位器 xpath 识别该元素。在 xpath中,我们可以使用 contains() 和 text() 函数。
让我们在页面中查找下面高亮显示的文本 −

xpath 表达式应该为 //*[contains(text(),'You are browsing')]。要获取该元素的文本,可以使用 getText 方法。让我们使用以下表达式从控制台选项卡中检查我们已经创建的 xpath 表达式:$x("//*[contains(text(),'You are browsing')]")。

示例
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class FindElmntsText{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://tutorialspoint.com/index.htm");
// identify element with text
WebElement i=
driver.findElement
(By.xpath("//*[contains(text(), 'You are browsing')]"));
// get text for element
System.out.println("Text is: " + i.getText());
}
driver.close();
}输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP