如何在 Selenium 中根據頁面上可見的文字識別元素?


要識別以文字形式顯示在頁面上的元素,在 xpath 中使用 text() 方法。

語法

driver.findElement(By.xpath("//tagname[text()=’value’]"))

示例

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
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://tutorialspoint.tw/index.htm";
      driver.get(url);
      driver.manage().window().maximize();
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      //xpath with text() method
      driver.findElement(By.xpath("//*[text()=’GATE Exams’]")).click();
      driver.close();
   }
}

更新日期:2020-06-10

2K+ 瀏覽量

開啟 職業生涯

完成課程,獲得認證

開始學習
廣告