如何在 Selenium Webdriver 中查找包含特定文本的元素?

seleniumautomation testingtesting tools更新于 2026/2/12 12:37:17

我们可以在 Selenium 中找到屏幕上显示特定文本的元素。这可以通过 xpath 定位器实现。xpath 定位器包含一些内置函数,可帮助创建自定义 xpath。

我们考虑如下网页的一部分 −

  • text() − 它是一个内置函数,用于根据屏幕上显示的文本识别元素。例如,如果我们想从上述网页中识别"Library"(图书馆),则带有 text() 的自定义 xpath 应该是 −

语法

//*[text()='Library']
  • contains() − 是一个内置函数,用于根据部分文本匹配来识别元素。例如,如果我们想从上述网页中识别"GATE 考试",则带有 contains() 的自定义 xpath 应该是

语法

//*[contains(text(),'GATE')]

示例

Code Implementation .

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 TextMatch{
   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(12, TimeUnit.SECONDS);
      // 使用 text() 识别元素
      WebElement l=driver.findElement(By.xpath("//*[text()='Library']"));
      // 使用 contains() 识别元素
      WebElement m=driver.findElement(By.xpath("//*[contains(text(),'GATE')]"));
      System.out.println("Element with text(): " + l.getText());
      System.out.println("Element with contains(): " + m.getText());
      driver.quit();
   }
}

输出


相关文章