如何使用 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.tw/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.tw/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