如何使用Selenium获取HTML表格中每个单元格的文本?


我们可以使用Selenium webdriver获取HTML表格中每个单元格的文本。<table>标签用于在html文档中定义表格。表格由<tr>表示的行和<td>表示的列组成。表头由<th>标签标识。

让我们考虑一个表格,我们将从中获取每个单元格的文本。

自动化工具类型链接
Selenium开源https://www.selenium.org/
UFT商业版统一功能测试器 (UNified Functional Tester)
Ranorex商业版https://www.ranorex.com/
TestComplete商业版TestComplete

让我们看看上面表格的HTML代码表示:

要检索表格的行数,我们将使用:

List<WebElement> rows =driver.findElements(By.tagName("tr"));

int rws_cnt= rows.size();

要检索表格的列数,我们将使用:

List<WebElement> cols =driver.findElements(By.tagName("td"));

int cols_cnt= cols.size();

示例

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 TableCellValue{
   public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
         WebDriver driver = new ChromeDriver();
         String u="https://sqengineer.com/practice-sites/practice-tables-selenium/";
         driver.get(u);
         driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
         // identify table
         WebElement t = driver.findElement(By.xpath("//*[@id='table1']/tbody"));
         // count rows with size() method
         List<WebElement> rws = t.findElements(By.tagName("tr"));
         int rws_cnt = rws.size();
         //iterate rows of table
         for (int i = 0;i < rws_cnt; i++) {
         // count columns with size() method
         List<WebElement> cols = rws.get(i).findElements(By.tagName("td"));
         int cols_cnt = cols.size();
         //iterate cols of table
         for (int j = 0;j < cols_cnt; j++) {
         // get cell text with getText()
         String c = cols.get(j).getText();
      System.out.println("The cell value is: " + c);
   }
}
      driver.quit();
   }
}

输出

更新于:2020年9月18日

5K+ 次浏览

启动您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.