他们在分数框上使用某种 Javascript,所以你将不得不玩更聪明的技巧(我的换行符):
/* box of awesome */
// iscurrentweek ? true;
(new nfl.scores.Game('2009112905','54635',{state:'pre',container:'scorebox-2009112905',
wrapper:'sb-wrapper-2009112905',template:($('scorebox-2009112905').innerHTML),homeabbr:'NYJ',
awayabbr:'CAR'}));
但是,为了回答您的问题,BeautifulSoup 解析它(似乎)很好:
fp = urlopen("http://www.nfl.com/scores")
data = ""
while 1:
r = fp.read()
if not r:
break
data += r
fp.close()
soup = BeautifulSoup(data)
print soup.contents[2].contents[1].contents[1]
输出:
<title>NFL Scores: 2009 - Week 12</title>
在我看来,可能更容易刮掉雅虎的 NFL 记分牌……事实上,去试试吧。
编辑:以您的问题为借口来学习 BeautifulSoup。Alex Martelli 一直在歌颂它,所以我认为值得一试——伙计,我印象深刻吗?
无论如何,我能够从 Yahoo! 制作一个基本的分数刮板!记分牌,像这样:
def main():
soup = BeautifulSoup(YAHOO_SCOREBOARD)
on_first_team = True
scores = []
hold = None
# Iterate the tr that contains a team's box score
for item in soup(name="tr", attrs={"align": "center", "class": "ysptblclbg5"}):
# Easy
team = item.b.a.string
# Get the box scores since we're industrious
boxscore = []
for quarter in item(name="td", attrs={"class": "yspscores"}):
boxscore.append(int(quarter.string))
# Final score
sub = item(name="span", attrs={"class": "yspscores"})[0]
if sub.b:
# Winning score
final = int(sub.b.string)
else:
data = sub.string.replace(" ", "")
if ":" in data:
# Catch TV: XXX and 0:00pm ET
final = None
else:
try: final = int(data)
except: final = None
if on_first_team:
hold = { team : (boxscore, final) }
on_first_team = False
else:
hold[team] = (boxscore, final)
scores.append(hold)
on_first_team = True
for game in scores:
print "--- Game ---"
for team in game:
print team, game[team]
我会在周日调整它,看看它是如何运作的,因为它真的很粗糙。这是它现在输出的内容:
--- Game ---
Green Bay ([0, 13, 14, 7], 34)
Detroit ([7, 0, 0, 5], 12)
--- Game ---
Oakland ([0, 0, 7, 0], 7)
Dallas ([3, 14, 0, 7], 24)
看那个,我也抢到了盒子分数......对于尚未发生的游戏,我们得到:
--- Game ---
Washington ([], None)
Philadelphia ([], None)
无论如何,一个钉子让你跳。祝你好运。