Python错误'KeyError:0'请求帮助

时间:2013-07-20 18:13:13

标签: 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 self.attrs[key]

这是我的类定义,以及随后对它的调用(顺便说一下,我知道代码可能是冗长的和非pythonic的;'new to python'中的'new'不能强调。):< / p>

def main():
    pass

if __name__ == '__main__':
    main()

import urllib.request
import datetime
from bs4 import BeautifulSoup

class EarningsAnnouncement:
    def __init__(self, Company, Ticker, EPSEst, AnnouncementDate, AnnouncementTime):
        self.Company = Company
        self.Ticker = Ticker
        self.EPSEst = EPSEst
        self.AnnouncementDate = AnnouncementDate
        self.AnnouncementTime = AnnouncementTime


webBaseStr = 'http://biz.yahoo.com/research/earncal/'
earningsAnnouncements = []

for dte in range(1, 30):
    dayVar = datetime.date.today()
    #currDay = str(dayVar.day)
    currDay = '22' #for debugging purposes
    currMonth = str(dayVar.month)
    currYear = str(dayVar.year)
    if (len(currDay)==1): currDay = '0' + currDay
    if (len(currMonth)==1): currMonth = '0' + currMonth
    dateStr = currYear + currMonth + currDay
    webString = webBaseStr + dateStr + '.html'
    with urllib.request.urlopen(webString) as url: page = url.read()
    soup = BeautifulSoup(page)
    tbls = soup.findAll('table')
    tbl6= tbls[6]
    rows = tbl6.findAll('tr')
    rows = rows[2:]
    for earn in rows:
        earningsAnnouncements.append(EarningsAnnouncement(earn[0], earn[1], earn[3], dateStr, earn[3]))

1 个答案:

答案 0 :(得分:2)

for earn in rows:
        earningsAnnouncements.append(EarningsAnnouncement(earn[0], earn[1], earn[3], dateStr, earn[3]))

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

>>> soup = BeautifulSoup('<tr class="hello">aaa</tr><tr>bbb</tr>')
>>> trs = soup.find_all('tr')
>>> trs[0]['class']
['hello']
>>>

没有名为0的属性,因此引发了KeyError。如果要访问标记的内容,则应使用earn.contents[0]