我正在尝试按列解析 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);
}
}
}
所以我的问题是,在我浏览完具有行跨度的列后,行中单元格的位置与其列不对应。
仅仅从单元格中获取所有数据并不是一个选择,因为我需要标题中的日期来正确保存数据。
最佳答案
终于成功了。我添加了一个数组来跟踪我的行跨度。通过此偏移量,我可以访问层次结构中属于上一列的 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/