2010-09-16 77 views
0

我有一個HTML表格,我試圖從中解析信息。但是,有些表跨越多行/列,所以我想要做的就是使用像BeautifulSoup這樣的表來將表解析爲某種類型的Python結構。我想只是用一個列表的列表,所以我會變成類似BeautifulSoup或正則表達式的HTML表格到數據結構?

<tr> 
    <td>1,1</td> 
    <td>1,2</td> 
</tr> 
<tr> 
    <td>2,1</td> 
    <td>2,2</td> 
</tr> 

[['1,1', '1,2'], 
['2,1', '2,2']] 

這一點我(覺得)應該是相當簡單的。但是,由於某些單元格跨越多行/列,因此會有一些輕微的複雜性。另外還有很多完全不必要的信息:

<td ondblclick="DoAdd('/student_center/sc_all_rooms/d05/09/2010/editformnew?display=W&amp;style=L&amp;positioning=A&amp;adddirect=yes&amp;accessid=CreateNewEdit&amp;filterblock=N&amp;popeditform=yes&amp;returncalendar=student_center/sc_all_rooms')" 
    class="listdefaultmonthbg" 
    style="cursor:crosshair;" 
    width="5%" 
    nowrap="1" 
    rowspan="1"> 
     <a class="listdatelink" 
      href="/student_center/sc_all_rooms/d05/09/2010/edit?style=L&amp;display=W&amp;positioning=A&amp;filterblock=N&amp;adddirect=yes&amp;accessid=CreateNewEdit">Sep 5</a> 
    </td> 

而且代碼真的看起來更糟。我真正需要出有:

<td rowspan="1">Sep 5</td> 

兩行後,有一個用17一個行跨度多行跨度,我想是這樣的:

<tr> 
    <td rowspan="2">Sep 5</td> 
    <td>Some event</td> 
</tr> 
<tr> 
    <td>Some other event</td> 
</tr> 

將結束出這樣的:

[["Sep 5", "Some event"], 
[None, "Some other event"]] 

有頁面上的多個表,我可以找到一個我想了,我只是不知道如何解析出我需要的信息。我知道我可以使用BeautfulSoup來「RenderContents」,但在某些情況下,我需要刪除鏈接標記(同時保留文本)。

我在想的過程是這樣的:

  1. 查找表
  2. 計數行的表
  3. 創建列表
  4. 解析表到列表(BeautifulSoup語法??(len(table.findAll('tr'))?) ?)
  5. ???
  6. 利潤! (嗯,這是一個純粹的內部程序,所以不是真的...)

回答

0

你可能需要確定一些ATTRS,ID或名稱表。

from BeautifulSoup import BeautifulSoup 

data = """ 
<table> 
<tr> 
    <td>1,1</td> 
    <td>1,2</td> 
</tr> 
<tr> 
    <td>2,1</td> 
    <td>2,2</td> 
</tr> 
</table> 
""" 

soup = BeautifulSoup(data) 

for t in soup.findAll('table'): 
    for tr in t.findAll('tr'): 
     print [td.contents for td in tr.findAll('td')] 

編輯:如果有多個鏈接,程序應該做什麼?

例:

<td><a href="#">A</a> B <a href="#">C</a></td>