我是 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]))