java - 按列解析 HTML 表格

标签 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);
        }
    }
}

所以我的问题是,在我浏览完具有行跨度的列后,行中单元格的位置与其列不对应。

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

最佳答案

终于成功了。我添加了一个数组来跟踪我的行跨度。通过此偏移量,我可以访问层次结构中属于上一列的 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
        }
    }
}

关于java - 按列解析 HTML 表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20495366/

相关文章:

java - 使用 SQLite4java 中的数据填充 JTable 的最佳方法

coldfusion - Jsoup 在 CFscript 上发布数据并解析替代 URL

java - 如何删除 Jsoup 输出段落中段落之间的空格?

java - 将网页写入文本文档

html - 设置与 CSS 边框不冲突的表格边框

html - 为什么html表格有多个列的数据到一列

java - 如何在数组中搜索奇数索引元素

Java - 跨服务器散列/加密

java - 使 Action 监听器(数组)更改值

javascript - 动态表格 HTML Javascript