gpt4 book ai didi

java - 按列解析 HTML 表格

转载 作者:行者123 更新时间:2023-11-30 07:12:16 25 4
gpt4 key购买 nike

我正在尝试按列解析 HTML 表格,我认为我已经掌握了正确的通用算法。但是 rowspans 给我带来了麻烦。

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com