如何使用 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. ");
      }
   }
}

輸出

更新於: 2020-08-28

18K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告