我有一個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&style=L&positioning=A&adddirect=yes&accessid=CreateNewEdit&filterblock=N&popeditform=yes&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&display=W&positioning=A&filterblock=N&adddirect=yes&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」,但在某些情況下,我需要刪除鏈接標記(同時保留文本)。
我在想的過程是這樣的:
- 查找表
- 計數行的表
- 創建列表
- 解析表到列表(BeautifulSoup語法??(
len(table.findAll('tr'))
?) ?) - ???
- 利潤! (嗯,這是一個純粹的內部程序,所以不是真的...)
LXML已經輕鬆了許多用至今。 – 2010-09-16 15:45:03