Reputation: 2640
I'm new to python, and I'm trying to implement a simple class, with instances to be added to a list. I'm getting the error 'KeyError:0' It's getting thrown in the file 'element.py' here:
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]
Here is my class definition, and subsequent call to it (by the way I know the code is likely verbose and non- pythonic; the 'new' in 'new to python' can't be stressed enough.):
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]))
Upvotes: 1
Views: 3065
Reputation: 8610
for earn in rows:
earningsAnnouncements.append(EarningsAnnouncement(earn[0], earn[1], earn[3], dateStr, earn[3]))
earn
is a tag
object representing a tr
element and his desendants in the HTML. And the []
on a tag is used to access the attributes of the tag. For example:
>>> soup = BeautifulSoup('<tr class="hello">aaa</tr><tr>bbb</tr>')
>>> trs = soup.find_all('tr')
>>> trs[0]['class']
['hello']
>>>
There is no attribute named 0
so a KeyError raised. If you want to access the contents of the tag, you should use earn.contents[0]
.
Upvotes: 2