【发布时间】:2017-11-01 07:52:53
【问题描述】:
我在使用 BeautifulSoup 解析表数据时遇到问题,尽管我尝试了许多解决方案,发现 here、here 和 here。我不想再问,但也许我的问题是独一无二的,这就是为什么上述解决方案没有奏效,或者我只是个白痴。
所以我正在尝试从water.weather.gov 检索任何给定河流的洪水触发器。我正在使用Mississippi river data,因为它拥有最活跃的测量站。每个电台都有 4 个我想要获得的阶段触发器:Action、Flood、Moderate 和 Major。我实际上已经能够提取这些类别的表格数据当有数值时,但是在表格数据为“不可用”的情况下,该行将被跳过,这样当我将值放在正确的阶段时,它们不会与适当的站触发器对齐。
我尝试提取的表格数据如下所示:
<div class="box_square"> <b><b>Flood Categories (in feet)</b><br>
</b>
<table width="150" cellspacing="0" cellpadding="0" border="0">
<tbody>
<tr><td nowrap="">Not Available</td></tr>
</tbody>
<div class="box_square"> <b><b>Flood Categories (in feet)</b><br>
</b>
<table width="150" cellspacing="0" cellpadding="0" border="0">
<tbody>
<tr style="display:'';line-height:20px;background-color:#CC33FF;color:black">
<td scope="col" nowrap="">Major Flood Stage:</td>
<td scope="col">18</td>
</tr>
<tr style="display:'';line-height:20px;background-color:#FF0000;color:white">
<td scope="col" nowrap="">Moderate Flood Stage:</td>
<td scope="col">15</td>
</tr>
<tr style="display:'';line-height:20px;background-color:#FF9900;color:black">
<td scope="col" nowrap="">Flood Stage:</td>
<td scope="col">13</td>
</tr>
<tr style="display:'';line-height:20px;background-color:#FFFF00;color:black">
<td scope="col" nowrap="">Action Stage:</td>
<td scope="col">12</td>
</tr>
<tr style="display:none;line-height:20px;background-color:#906320;color:white">
<td scope="col" nowrap="">Low Stage (in feet):</td>
<td scope="col">-9999</td>
</tr>
</tbody>
</table><br></div>
最后一个Low Stage不是必须的,我已经过滤掉了。这是我拥有的代码,它将使用适当的值填充 alert_list,但没有必要的 Not Available:
alert_list = []
alert_values = []
alerts = soup.findAll('td', attrs={'scope':'col'})
for alert in alerts:
alert_list.append(alert.text.strip())
a_values = alert_list[1::2]
alert_list.clear()
major_lvl = a_values[::5]
moderate_lvl = a_values[1::5]
flood_lvl = a_values[2::5]
action_lvl = a_values[3::5]
结果:
>>> major_lvl
['18', '26', '0', '11', '0', '17', '17', '18', '0', '683', '16', '0', '20', '16', '18', '665', '661', '18', '651', '645', '15.5', '636', '20', '631', '22', '21', '20.5', '21.5', '20', '20', '20.5', '13.5', '18', '18', '20', '18.5', '17', '14', '18', '19', '25', '25', '25', '26', '25', '24', '22', '25', '33', '34', '29', '34', '40', '40', '0', '0', '0', '42', '42', '0', '0', '0', '0', '0', '44', '47', '43', '35', '46', '52', '55', '0', '44', '57', '50', '57', '64', '40', '34', '26', '20']
我只是注意到实际上 Not Available 标签没有被抓取的原因是因为它在 tr 标签下,而不是 td .我如何添加它以使我的值对齐?
【问题讨论】:
标签: python web-scraping beautifulsoup html-table