Python错误';KeyError:0';请求的援助

Python错误';KeyError:0';请求的援助,python,beautifulsoup,Python,Beautifulsoup,我是python新手,我正在尝试实现一个简单的类,将实例添加到列表中。我收到错误“KeyError:0”,它被抛出到文件“element.py”中,如下所示: def __getitem__(self, key): """tag[key] returns the value of the 'key' attribute for the tag, and throws an exception if it's not there.""" return

我是python新手,我正在尝试实现一个简单的类,将实例添加到列表中。我收到错误“KeyError:0”,它被抛出到文件“element.py”中,如下所示:

def __getitem__(self, key):
        """tag[key] returns the value of the 'key' attribute for the tag,
        and throws an exception if it's not there."""
        return self.attrs[key]
这是我的类定义,以及随后对它的调用(顺便说一句,我知道代码可能是冗长的、非python的;在“newtopython”中的“new”怎么强调都不过分。):

earn
是一个
标记
对象,表示HTML中的
tr
元素及其desendant。标签上的
[]
用于访问标签的属性。例如:

>>> soup = BeautifulSoup('<tr class="hello">aaa</tr><tr>bbb</tr>')
>>> trs = soup.find_all('tr')
>>> trs[0]['class']
['hello']
>>>
>soup=BeautifulSoup('aaabb'))
>>>trs=汤。查找所有('tr')
>>>trs[0][“类”]
[你好]
>>>
没有名为
0
的属性,因此引发了KeyError。如果要访问标记的内容,应使用
earn.contents[0]

for earn in rows:
        earningsAnnouncements.append(EarningsAnnouncement(earn[0], earn[1], earn[3], dateStr, earn[3]))
>>> soup = BeautifulSoup('<tr class="hello">aaa</tr><tr>bbb</tr>')
>>> trs = soup.find_all('tr')
>>> trs[0]['class']
['hello']
>>>