0

我是 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 语言;“python 新手”中的“新”不能足够强调。):

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]))
4

1 回答 1

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

earn是一个tag对象,表示trHTML 中的元素及其后代。而[]on a 标签用于访问标签的属性。例如:

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

没有命名属性0,因此引发了 KeyError。如果你想访问标签的内容,你应该使用earn.contents[0].

于 2013-07-20T18:27:53.847 回答