pythonbs:获取包含和不包含颜色属性的行

2024-10-08 19:22:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些类似这样的html(它表示表中的数据行,即tr/tr之间的数据是表中的一行)

<tr bgcolor="#f4f4f4">
<td height="25" nowrap="NOWRAP">&nbsp;CME_ES&nbsp;</td>
<td height="25" nowrap="NOWRAP">&nbsp;07:58:46&nbsp;</td>
<td height="25" nowrap="NOWRAP">&nbsp;Connected&nbsp;</td>
<td height="25" nowrap="NOWRAP">&nbsp;0&nbsp;</td>
<td height="25" nowrap="NOWRAP">&nbsp;0&nbsp;</td>
<td height="25" nowrap="NOWRAP">&nbsp;0&nbsp;</td>
<td height="25" nowrap="NOWRAP">&nbsp;0&nbsp;</td>
<td height="25" nowrap="NOWRAP">&nbsp;07:58:00&nbsp;</td>
**<td height="25" nowrap="NOWRAP" bgcolor="#55aa2a">&nbsp;--:--:--&nbsp;</td>**
<td height="25" nowrap="NOWRAP">&nbsp;0&nbsp;</td>
<td height="25" nowrap="NOWRAP">&nbsp;0&nbsp;</td>
<td height="25" nowrap="NOWRAP">&nbsp;01:25:00 &nbsp;</td>
<td height="25" nowrap="NOWRAP">&nbsp; 22:00:00&nbsp;</td>
</tr>
.
.
.
<tr bgcolor="#ffffff">
<td height="25" nowrap="NOWRAP">&nbsp;CME_NQ&nbsp;</td>
<td height="25" nowrap="NOWRAP">&nbsp;07:58:46&nbsp;</td>
<td height="25" nowrap="NOWRAP">&nbsp;Connected&nbsp;</td>
<td height="25" nowrap="NOWRAP">&nbsp;0&nbsp;</td>
<td height="25" nowrap="NOWRAP">&nbsp;0&nbsp;</td>
<td height="25" nowrap="NOWRAP">&nbsp;191&nbsp;</td>
<td height="25" nowrap="NOWRAP">&nbsp;0&nbsp;</td>
<td height="25" nowrap="NOWRAP">&nbsp;07:58:01&nbsp;</td>
**<td height="25" nowrap="NOWRAP">&nbsp;--:--:--&nbsp;</td>**
<td height="25" nowrap="NOWRAP">&nbsp;0&nbsp;</td>
<td height="25" nowrap="NOWRAP">&nbsp;0&nbsp;</td>
<td height="25" nowrap="NOWRAP">&nbsp;01:25:00 &nbsp;</td>
<td height="25" nowrap="NOWRAP">&nbsp; 22:00:00&nbsp;</td>
</tr>

我有从每一行集合中获取颜色的代码:

mrkt_stat = []
for td in site.findAll('td'):
 if 'bgcolor' in td.attrs:
  mrkt_stat.append(td.attrs['bgcolor'])

问题是,当行集合没有bgcolor属性时,没有数据添加到mrkt_stat列表中。你知道吗

我该如何删除它,以便即使一行没有bgcolor attr,它仍然会作为NULL或N/a添加到列表中?你知道吗

知道bgcolor attr(可能存在也可能不存在)总是出现在行集合的第9行中是很有用的,不管该行是否有attr(请看用**括起来的html行)

编辑:输出应如下所示(每行集合第9行的所有颜色属性列表,如果没有颜色属性,则显示“N/a”):

['#55aa2a',...,'N/A'] 

Tags: 数据列表属性颜色htmltrstattd
2条回答

我想出了解决这个问题的办法,虽然这是一个相当长的方法,但解决了这个问题

keys = []
for tr in site.find_all('br'):
    for td in site.find_all('tr'):
        if td in keys:
            pass
        else:
            keys.append(td)
del keys[:4]

for i in range(0, len(keys)):
    g = keys[i]
    color = []

    for line in g:
        color.append(line)

    del color[:17]

    check = []
    h = color[0]
    if 'bgcolor' in h.attrs:
        check.append(h['bgcolor'])
    else:
        check.append('N/A')

总结到第h = color[0]行,我将行集合的第9行存储到变量h中,然后检查bgcolor是否在这个标记的属性中。如果是,则将其添加到check列表中如果不是,则改为添加'N/A'

如果您能想出缩短此方法,我们将不胜感激:)!你知道吗

您可以将else语句添加到if语句中:

mrkt_stat = []

for td in site.findAll('td'):
    if 'bgcolor' in td.attrs:
        mrkt_stat.append(td.attrs['bgcolor'])
    else:
        mrkt_stat.append('N/A')

相关问题 更多 >

    热门问题