On this page the final score (number) of each team has the same class name class="finalScore"
.
When I call the final score of the away team (on top) the code calls that number without a problem. If ... favLastGM = 'A'
When I try to call the final score of the home team (on bottom) the code gives me an error. If ... favLastGM = 'H'
Below is my code:
import pickle
import math
import urllib2
from lxml import etree
from bs4 import BeautifulSoup
from urllib import urlopen
#Last Two Game info Home [H] or Away [A]
favLastGM = 'A' #Higher week number 2
#Game Info (Favorite) Last Game Played - CBS Sports (Change Every Week)
favPrevGMInfoUrl = 'http://www.cbssports.com/nfl/gametracker/boxscore/NFL_20140914_NE@MIN'
favPrevGMInfoHtml = urlopen(favPrevGMInfoUrl).read()
favPrevGMInfoSoup = BeautifulSoup(favPrevGMInfoHtml)
if favLastGM == 'A': #This Gives Final Score of Away Team - Away Score
favScore = favPrevGMInfoSoup.find_all("td", { "class" : "finalScore" })
elif favLastGM == 'H':
favScore = favPrevGMInfoSoup.find_all("td", { "class" : "finalScore" })[1]
else:
print("***************************************************")
print("NOT A VALID ENTRY - favLastGM !")
print("***************************************************")
print ("Enter: Total Points Allowed from Favored Team Defense for last game played: "),
print favScore[0].text
This is the error I get if favLastGM = 'H'
Traceback (most recent call last): File "C:/Users/jcmcdonald/Desktop/FinalScoreTest.py", line 26, in print favScore[0].text File "C:\Python27\lib\site-packages\bs4\element.py", line 905, in getitem return self.attrs[key] KeyError: 0
There are just two elements with
class="finalScore"
, the first is the score of the home team, the second is the score of the away team:FYI, instead of
.find_all("td", {"class": "finalScore"})
, you can use a CSS selector:.select("td.finalScore")
.