小编典典

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

selenium

在Selenium 2.0中,我不知道如何遍历网页中的HTML表。在selenium2.0 javadoc中,我找到了两个类“ TableFinder”和“
TableCellFinder”,但找不到任何示例。

我想做这样的事情:

RowCount=Get how many rows are there in the html table

for each row of the table
{
   column_count=Get column count
   for each column
   {
      cell_value=get_text_from(row,col);
      Do something with cell_value
   }
}

如何从每个表格单元格中获取文本?


阅读 541

收藏
2020-06-26

共1个答案

小编典典

感谢您的早日答复。

我找出了使用硒2.0类的解决方案。

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class WebTableExample 
{
    public static void main(String[] args) 
    {
        WebDriver driver = new InternetExplorerDriver();
        driver.get("http://localhost/test/test.html");

        WebElement table_element = driver.findElement(By.id("testTable"));
        List<WebElement> tr_collection=table_element.findElements(By.xpath("id('testTable')/tbody/tr"));

        System.out.println("NUMBER OF ROWS IN THIS TABLE = "+tr_collection.size());
        int row_num,col_num;
        row_num=1;
        for(WebElement trElement : tr_collection)
        {
            List<WebElement> td_collection=trElement.findElements(By.xpath("td"));
            System.out.println("NUMBER OF COLUMNS="+td_collection.size());
            col_num=1;
            for(WebElement tdElement : td_collection)
            {
                System.out.println("row # "+row_num+", col # "+col_num+ "text="+tdElement.getText());
                col_num++;
            }
            row_num++;
        } 
    }
}
2020-06-26