我正在使用 Beautiful Soup 进行网页抓取。我是新手。
问题1: 这是表格:
<table width="75%" align=center>
<tr>
<td><STRONG><font face="Arial" size=2>S.No:</font></STRONG></td>
<td><font face="Arial" size=2> 1635925</font></td>
</tr>
<tr>
<td><FONT size=2><STRONG><font face="Arial">Name:</font><br></STRONG></FONT></td>
<td><font face="Arial" size=2> <b>Alex</b></font></td>
</tr>
<tr>
<td><STRONG><font face="Arial" size=2>Dog's Name:</font></STRONG></td>
<td><font face="Arial" size=2> Tiger</font></td>
</tr>
<tr>
<td><STRONG><font face="Arial" size=2 >Cat's Name:</font></STRONG></td>
<td><font face="Arial" size=2>Pussy</font></td>
</tr>
</table>
这是参考上表的代码:
for row in soup('table')[4]('tr'):
tds = row('td')
print tds[0].string, tds[1].string
这是输出:
S.No: 1635925
None None
Dog's Name: Tiger
Cat's Name: Pussy
问题是第 2 行,为什么要打印两列None
?
问题2:与上述类似的问题
<tr bgcolor="#ffffff">
<td align="middle"><font face="Arial" size=2>503</font></td>
<td align="left"><font face="Arial" size=2>Text1</font></td>
<td align="left"><font face="Arial" size=2>---</font></td>
<td align="middle"><font face="Arial" size=2>2</font></td>
</tr>
<tr bgcolor="#e6e6fa">
<td colspan=4><font face="Arial" size=2> some random text</font></td>
</tr>
<tr >
<td align="middle"><font face="Arial" size=2>048</font> </td>
<td align="left"><font face="Arial" size=2>Text 2</font></td>
<td align="left"><font face="Arial" size=2>187 </font></td>
<td align="middle"><font face="Arial" size=2>2</font></td>
</tr>
我的代码:
for row in soup('table')[5]('tr'):
tds = row('td');
if len(tds) == 4:
print tds[0].string, tds[1].string, tds[2].string, tds[3].string
输出:
503 Text1 --- 2
None Text2 187 2
为什么第一列的文字是None
而不是048
?