我想问一下如何解析<table>
中的colspan和rowspan值。
例如:
<table cellpadding="2" cellspacing="2" border="1" width="50%">
<tbody>
<tr>
<td valign="top" rowspan="2" colspan="1" align="center">NO<br>
</td>
<td valign="top" rowspan="1" colspan="3" align="center">NAMA<br>
</td>
<td valign="top" rowspan="1" colspan="2" align="center">TELEPON<br>
</td>
<td valign="top" rowspan="2" colspan="1" align="center">KODE<br>
</td>
</tr>
<tr>
<td valign="top" align="center">DEPAN<br>
</td>
<td valign="top" align="center">TENGAH<br>
</td>
<td valign="top" align="center">BELAKANG<br>
</td>
<td valign="top" align="center">KODE<br>
</td>
<td valign="top" align="center">NO TLP<br>
</td>
</tr>
<tr>
<td valign="top" align="center">1<br>
</td>
<td valign="top">Ani<br>
</td>
<td valign="top">Tiara<br>
</td>
<td valign="top">Ramadika<br>
</td>
<td valign="top" align="center">021<br>
</td>
<td valign="top" align="center">8466729<br>
</td>
<td valign="top" align="center">17412<br>
</td>
</tr>
<tr>
<td valign="top" align="center">2<br>
</td>
<td valign="top">Dia<br>
</td>
<td valign="top">Andari<br>
</td>
<td valign="top">Putri<br>
</td>
<td valign="top" align="center">022<br>
</td>
<td valign="top" align="center">5930290<br>
</td>
<td valign="top" align="center">18291<br>
</td>
</tr>
<tr>
<td valign="top" align="center">3<br>
</td>
<td valign="top">Rangga<br>
</td>
<td valign="top">Dimas<br>
</td>
<td valign="top">Putra<br>
</td>
<td valign="top" align="center">023<br>
</td>
<td valign="top" align="center">8349829<br>
</td>
<td valign="top" align="center">13901<br>
</td>
</tr>
<tr>
<td valign="top" align="center">4<br>
</td>
<td valign="top">Niko<br>
</td>
<td valign="top">Reza<br>
</td>
<td valign="top">Anggara<br>
</td>
<td valign="top" align="center">024<br>
</td>
<td valign="top" align="center">4284982<br>
</td>
<td valign="top" align="center">21211<br>
</td>
</tr>
</tbody>
</table>
我使用python进行HTML解析,如下所示:
from bs4 import BeautifulSoup
soup = BeautifulSoup(html)
t = soup.find("table")
dat = [ map(str, row.findAll('td', { 'rowspan' })) for row in t.findAll("tr") ]
print dat[1]
但是,我还是很困惑如何得到
colspan
的值。我已经得到了解析标记表,但是我不知道如何获取
colspan
属性的值。我试过使用regex,但没有成功。 最佳答案
我建议使用CSS selectors:
from bs4 import BeautifulSoup
s = open("colspan_rowspan.html").read()
soup = BeautifulSoup(s)
# select all td children of tr that have both colspan & rowspan
tags = soup.select('tr td[colspan,rowspan]')
# print out the values, for example:
print [(td['colspan'], td['rowspan']) for tags]
# will return [('1', '2'), ('3', '1'), ('2', '1'), ('1', '2')]
关于html - beautifulSoup解析标记表HTML,尤其是colspan和rowspan,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13263373/