如何使用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.