如何从HTML表格的每个单元格中获取文本? [英] How to get text from each cell of an HTML table?

查看:157
本文介绍了如何从HTML表格的每个单元格中获取文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Selenium 2.0, I have no idea how to traverse through a HTML table in a webpage. In selenium2.0 javadoc, I found two classes "TableFinder" and "TableCellFinder", but I couldn't find any examples.

我想做这样的事情:

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
   }
}

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

How can I get the text from each of the table cells?

推荐答案

感谢您的早日答复.

我想出了使用硒2.0类的解决方案.

I figured out the solutions using selenium 2.0 classes.

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++;
        } 
    }
}

这篇关于如何从HTML表格的每个单元格中获取文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆