如何在 Selenium 中统计 Web 表格中的标题数量?

software testingautomation testingselenium web driver更新于 2026/2/10 15:22:17

可以使用 findElements() 方法统计 Web 表格中的标题总数。其逻辑是使用表格中的 <th> 标签,通过 xpath 返回 Web 元素列表,然后获取该列表的大小。

代码实现

示例

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;
import java.util.List;
public class TableHeaderCount {
   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/plsql/plsql_basic_syntax.htm";
      driver.get(url);
      driver.manage().window().maximize();
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      // 使用附加索引的 xpath 获取标题
      //借助 <th> 标签从表格第一行获取
      List<WebElement> header = driver.findElements(By.xpath("//table/tbody/tr[1]/th"));
      System.out.println(“The number of table headers is “+ header.size());
      driver.close();
   }
}

相关文章