如何使用 Selenium 检查页面中是否存在某些文本?
seleniumautomation testingtesting tools更新于 2026/1/8 6:37:17
我们可以使用 Selenium 检查页面中是否存在某些文本。查找文本的方法不止一种。我们可以使用 getPageSource() 方法获取完整的页面源代码,然后验证文本是否存在。此方法以字符串形式返回内容。
我们还可以使用带有 xpath 定位器的 findElements 方法检查某些文本是否存在。然后,我们将使用 text() 函数创建自定义 xpath。findElements() 方法返回一个元素列表。我们将使用 size() 方法来验证列表大小是否大于 0。
假设我们要验证页面中是否存在以下文本。

示例
Code Implementation with findElements().
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;
import java.util.List;
public class TextExistFindElemnts{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://www.tutorialspoint.com/index.htm";
driver.get(url);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
String t = "You are browsing the best resource for Online Education";
// 使用 text() 识别元素
List<WebElement> l= driver.findElements(By.xpath("//*[contains(text(),'You are browsin')]"));
// 验证列表大小
if ( l.size() > 0){
System.out.println("Text: " + t + " is present. ");
} else {
System.out.println("Text: " + t + " is not present. ");
}
}
}
示例
使用 getPageSource() 实现代码。
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 TextExistPgSource{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://www.tutorialspoint.com/index.htm";
driver.get(url);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
String t = "You are browsing the best resource for Online Education";
// getPageSource() 获取页面源
if ( driver.getPageSource().contains("You are browsin")){
System.out.println("Text: " + t + " is present. ");
} else {
System.out.println("Text: " + t + " is not present. ");
}
}
}
输出


