2013-12-10 44 views
2

我試圖按列解析HTML表,我想我已經有了一般的算法。但rowpans正在給我帶來麻煩。按列解析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); 
     } 
    } 
} 

所以我的問題是,小區的一排位置不符合其列對應,我已經後已經通過了一個rowpans列。

只是從單元格獲取所有數據不是一個選項,因爲我需要標題中的日期才能正確保存數據。

+0

+1我一直有跨越的問題,除了我正在使用的表具有colspans和行跨度這是非常可怕的。我的方法與你的方法類似,因爲我試圖跟蹤生成的跨度,但在我的情況下,我一直在追蹤行/ colspans類似於由row/col索引的二維數組,因爲它保持爲單數是不夠的。 – MxyL

+0

@MxyL是的,我一直在想這樣的事情,儘管我希望能有比這更優雅的東西。如果我能解決問題,我一定會在這裏發佈。 –

回答

4

終於得到了一些工作。我添加了一個數組來跟蹤我的rowspans。有了這個偏移量,我可以訪問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 
     } 
    } 
}