【发布时间】:2015-05-10 17:23:03
【问题描述】:
我正在尝试从网页中提取表格。下面是使用 beautifulsoup 的 HTML 和 Python 代码。下面的代码总是对我有用,但在这种情况下我会变得空白。提前致谢。
<table>
<thead>
<tr>
<th>Period Ending:</th>
<th class="TalignL">Trend</th>
<th>9/27/2014</th>
<th>9/28/2013</th>
<th>9/29/2012</th>
<th>9/24/2011</th>
</tr>
</thead>
<tr>
<th bgcolor="#E6E6E6">Total Revenue</th>
<td class="td_genTable"><table border="0" align="center" width="*" cellspacing="0" cellpadding="0"><tr><td align="bottom"><table border="0" height="100%" cellspacing="0" cellpadding="0"><tr><td><table cellspacing="0" cellpadding="0" border="0"><tr><td height="15" bgcolor="#47C3D3" width="6"></td><td height="15" bgcolor="#FFFFFF" width="1px"></td></tr><tr><td height="1" colspan="2" bgcolor="#D1D1D1"></td></tr></table></td><td><table cellspacing="0" cellpadding="0" border="0"><tr><td height="1" bgcolor="#FFFFFF" width="6"></td><td height="1" bgcolor="#FFFFFF" width="1px"></td></tr><tr><td height="14" bgcolor="#47C3D3" width="6"></td><td height="14" bgcolor="#FFFFFF" width="1px"></td></tr><tr><td height="1" colspan="2" bgcolor="#D1D1D1"></td></tr></table></td><td><table cellspacing="0" cellpadding="0" border="0"><tr><td height="2" bgcolor="#FFFFFF" width="6"></td><td height="2" bgcolor="#FFFFFF" width="1px"></td></tr><tr><td height="13" bgcolor="#47C3D3" width="6"></td><td height="13" bgcolor="#FFFFFF" width="1px"></td></tr><tr><td height="1" colspan="2" bgcolor="#D1D1D1"></td></tr></table></td><td><table cellspacing="0" cellpadding="0" border="0"><tr><td height="7" bgcolor="#FFFFFF" width="6"></td><td height="7" bgcolor="#FFFFFF" width="1px"></td></tr><tr><td height="8" bgcolor="#47C3D3" width="6"></td><td height="8" bgcolor="#FFFFFF" width="1px"></td></tr><tr><td height="1" colspan="1" bgcolor="#D1D1D1"></td></tr></table></td></tr></table></td></tr></table></td>
<td>$182,795,000</td>
<td>$170,910,000</td>
<td>$156,508,000</td>
<td>$108,249,000</td>
rows = table.findAll('tr')
for row in rows:
cols = row.findAll('td')
col1 = [ele.text.strip().replace(',','') for ele in cols]
account = col1[0:1]
period1 = col1[2:3]
period2 = col1[3:4]
period3 = col1[4:5]
record = (stock, account,period1,period3,period3)
print record
【问题讨论】:
-
您的第一个非标题行的第一列包含一个充满空单元格的表格,其中没有任何文本。您的代码正确地发现没有文本。我不确定你想让它做什么。
-
同时,您为什么使用已弃用的名称
findAll?您是从为 BS3 编写的示例代码中学习,而不是从 BS4 的更新示例或文档中学习吗? -
最后,
find_all(或findAll)搜索所有后代,而不仅仅是顶级子代。因此,除非您想遍历外部表的行和嵌入在该表列中的每个子表的行并将它们视为相同,否则您不应该在这里使用它。
标签: python html beautifulsoup