按列解析HTML表

时间:2013-12-10 13:04:49

标签: java jsoup html-table

我试图按列解析HTML表格,我认为我已经掌握了通用算法。但是,行距会给我带来麻烦。

Here is an example table.

这是我使用的代码:

Elements rows = document.select("table.asio_basic > tbody > tr"); // get all tablerows
Elements dataCells = new Elements(); //Object to save all cells with data

for (int i = 0; i < rows.get(0).children().size(); i++) //iterate through the columns.
{       
    for (int j = 0; j < rows.size(); j++) //iterate through the rows
    {
        Element cell = rows.get(j).child(i); //get the cell in row j, column i

        if (cell.hasAttr("rowspan"))
        {
            j += Integer.parseInt(cell.attr("rowspan")); // add rowspan to counter to skip nonexistent cells
            dataCells.add(cell);
        }
    }
}

所以我的问题是,在我通过带有行距的列之后,单元格的位置与其列不对应。

只是从单元格中获取所有数据不是一个选项,因为我需要从标题中的日期来正确保存数据。

1 个答案:

答案 0 :(得分:4)

终于成功了。我添加了一个数组来跟踪我的rowpans。通过此偏移量,我可以访问层次结构中属于上一列的td

这是我的代码。我稍微更改了它以适用于rowspans的任何表格。

Document document = document = Jsoup.connect(URL).get(); //get the HTML page
Elements rows = document.select("table > tbody > tr"); //select all rows
int[] offsets = new int[rows.size()];

for (int i = 0; i < rows.get(0).children().size(); i++) //unless colspans are used, this should return the number of columns
{
    for (int j = 0; j < rows.size(); // loops through the rows of each column
    {
        Element cell = rows.get(j).child(i + offsets[j]); //get an individual cell

        if (cell.hasAttr("rowspan")) //if that cell has a rowspan
        {
            int rowspan = Integer.parseInt(cell.attr("rowspan"));

            for (int k = 1; k < rowspan; k++)
            {
                offsets[j + k]--; //add offsets to rows that now have a cell "missing"
            }

            j += rowspan - 1; //add rowspan to index, to skip the "missing" cells
        }
    }
}
相关问题