如何使用 Selenium 检查页面中是否存在某些文本?
我们可以使用 Selenium 检查页面中是否存在某些文本。有多种方法可以找到它。我们可以使用 getPageSource() 方法获取完整的页面源代码,然后验证文本是否存在。此方法以字符串形式返回内容。
我们还可以借助 findElements 方法和 xpath 定位符来检查是否存在某些文本。然后,我们将使用 text() 函数创建一个自定义的 xpath。findElements() 方法返回一个元素列表。我们将使用 size() 方法来验证列表大小是否大于 0。
假设我们想验证以下文本是否在页面中存在。

示例
使用 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://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";
// identify elements with text()
List<WebElement> l= driver.findElements(By.xpath("//*[contains(text(),'You are browsin')]"));
// verify list size
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://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() to get page source
if ( driver.getPageSource().contains("You are browsin")){
System.out.println("Text: " + t + " is present. ");
} else {
System.out.println("Text: " + t + " is not present. ");
}
}
}输出

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