2013-12-10 3 views
2

HTML 테이블을 열로 구문 분석하려고하는데 일반적으로 알고리즘이 올바르다 고 생각합니다. 하지만 행렬 때문에 문제가 생겼습니다. 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); 
     } 
    } 
} 

내 문제 행에있는 셀의 위치가 내가 한 후에는 열이 일치하지 않는다는 것입니다 rowspans가있는 열을 통과했습니다.

데이터를 올바르게 저장하기 위해 헤더의 날짜가 필요하므로 셀에서 모든 데이터를 가져 오는 것은 옵션이 아닙니다.

+0

+1 나는 함께 일하는 테이블이 colspans와 행 범위가 끔찍한 것을 제외하고는 스패닝 문제도 있습니다. 내 접근 방식은 당신과 비슷하지만, 스패닝을 추적하려고하지만, 제 경우에는 행/colspan을 2D 배열처럼 행/colsp로 인덱싱하는 것과 같은 방식으로 추적하고 있습니다. 단일 번호로는 충분하지 않습니다. – 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 
     } 
    } 
} 
관련 문제