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

Vik*_*kas 25 selenium selenium-webdriver

在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
   }
}
Run Code Online (Sandbox Code Playgroud)

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

Vik*_*kas 47

谢谢你早些时候的回复.

我找到了使用selenium 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++;
        } 
    }
}
Run Code Online (Sandbox Code Playgroud)


Chr*_*sth 8

这是我刚刚编写的C#示例,松散地基于使用CSS选择器的答案,希望能够使用其他人来查看如何设置ReadOnlyCollection表行并至少在MS域中迭代它.我正在查看表行的集合,以查找带有OriginatorsRef(只是一个字符串)的行和TD带有包含title属性的图像Overdue by:

    public ReadOnlyCollection<IWebElement> GetTableRows()
    {
        this.iwebElement = GetElement();
        return this.iwebElement.FindElements(By.CssSelector("tbody tr"));
    }
Run Code Online (Sandbox Code Playgroud)

在我的主要代码中:

        ...
        ReadOnlyCollection<IWebElement> TableRows;
        TableRows = f.Grid_Fault.GetTableRows();

        foreach (IWebElement row in TableRows)
        {
            if (row.Text.Contains(CustomTestContext.Current.OriginatorsRef) &&
              row.FindElements(By.CssSelector("td img[title*='Overdue by']")).Count > 0)
                return true;
        }
Run Code Online (Sandbox Code Playgroud)