迭代可变数量的 table 行时出现 IndexError

Getting IndexError when iterating changeable number of table rows

我正在使用 BeautifulSoup 4.4 在网站上的 table 中抓取 不断变化的行数。在下面的代码中有四个 tables - 但它每天都在不断变化。

主要问题

  • 如何摆脱 IndexError 消息?

状态:我正在尝试将可迭代项的数量设置为最大迭代次数(但这并没有解决实际问题)。

子题

  • 我正计划将输出附加到文件中 - 索引错误吗 迭代此 table 以任何方式影响数据输出或与迭代相关的其他进程? (我还是想避免报错信息 不管怎样)。

索引错误信息: item_name = strengths.findAll('tr')[x].findAll('td')[0].get_text() IndexError: list index out of range

<tbody>
    <tr>
        <td>
            <div class="iconize iconize-icon-left">
                <span class="incidents-icon" title="Description"></span>
                Heinz 57 ketchup 
            </div>
        </td>
        <td style="text-align: right;">
            <span class="level">Popular</span>
        </td>
    </tr>
<tr> # same structure as the tr above
<tr> # same structure as the tr above
<tr> # same structure as the tr above
</tbody>

到目前为止我的代码:

strengths = strengths_div.table.tbody

output = []

iter_length = len(list(strengths)) # Finding out the number of iterable elements

x = 0 # counter 

for tr in strengths:
    while x <= int(iter_length):  

    item_name = strengths.findAll('tr')[x].findAll('td')[0].get_text()
    strength_value = strengths.findAll('tr')[x].findAll('td')[1].get_text()
    item_name = item_name.strip()
    strength_value = strength_value.strip()

    x = x + 1

首先,如果你要使用索引,你不想使用x = len(iterable),因为长度为n的iterable不会有索引n。最大的索引是 n - 1,所以 while 循环行应该这样开始:while x < int(iter_length):。另外,我不明白你的外部 for 循环的目的,因为你没有在我能看到的循环中的任何地方使用 tr

避免索引错误的一个好方法是遍历可迭代对象中的项目而不是遍历其索引。它通常也使代码更整洁、更易于阅读。这是我会做的:

for items in strengths.findAll('tr'):

    item_name = items.findAll('td')[0].get_text()
    strength_value = items.findAll('td')[1].get_text()
    item_name = item_name.strip()
    strength_value = strength_value.strip()