Java 按列分析HTML表

Java 按列分析HTML表,java,jsoup,html-table,Java,Jsoup,Html Table,我正在尝试按列解析一个HTML表,我认为我的通用算法是正确的。但是吵闹给我带来了麻烦 这是我正在使用的代码: 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

我正在尝试按列解析一个HTML表,我认为我的通用算法是正确的。但是吵闹给我带来了麻烦

这是我正在使用的代码:

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);
        }
    }
}
所以我的问题是,在我通过一个具有行跨度的列之后,单元格在一行中的位置与其列不对应


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

最终设法使某些内容正常工作。我添加了一个数组来跟踪行间距。通过这个偏移量,我可以访问层次结构中属于上一列的tds

这是我的密码。我稍微修改了它,以适用于任何具有行跨度的表


终于设法使一些东西起作用了。我添加了一个数组来跟踪行间距。通过这个偏移量,我可以访问层次结构中属于上一列的tds

这是我的密码。我稍微修改了它,以适用于任何具有行跨度的表


+1我在跨越方面也遇到了一些问题,除了我正在使用的表同时有colspan和row span,这非常糟糕。我的方法与你的方法类似,我试图跟踪跨距,但在我的例子中,我一直在跟踪行/列跨距,类似于由行/列索引的2D数组,因为仅将其作为单个数字是不够的。@MxyL是的,我也在考虑类似的事情,虽然我希望会有比这更优雅的东西。如果我真的解决了一些问题,我一定会把它贴在这里。+1我在跨越方面也遇到了问题,除了我正在使用的表同时有colspan和row span,这太糟糕了。我的方法与你的方法类似,我试图跟踪跨距,但在我的例子中,我一直在跟踪行/列跨距,类似于由行/列索引的2D数组,因为仅将其作为单个数字是不够的。@MxyL是的,我也在考虑类似的事情,虽然我希望会有比这更优雅的东西。如果我真的解决了一些问题,我一定会把它贴在这里。
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
        }
    }
}