Если приведенный ниже скрипт запускается, он начинается со всех людей, которых я хотел бы (пример: Ник Ахмед, Алекс Авила и т. Д.).Но дает мне KeyError: 'row'
после 9 или около того.
SCRIPT .
import csv
import requests
import datetime
from pprint import pprint
# GET TEAM ID AND STORE AS team_id
req = requests.get('http://lookup-service-prod.mlb.com/json/named.team_all_season.bam?sport_code=%27mlb%27&all_star_sw=%27N%27&sort_order=name_asc&season=%272018%27')
data = req.json()['team_all_season']['queryResults']['row']
for teams in data:
team_id = teams['team_id']
team = teams['name_abbrev']
# GET PLAYER ID using team_id string and store PLAYER ID as playerId
req1 = requests.get('http://lookup-service-prod.mlb.com/json/named.roster_40.bam?team_id=' + str(team_id) + '')
roster = req1.json()['roster_40']['queryResults']['row']
for info in roster:
player = info['name_display_first_last']
playerId = info['player_id']
# Use playerId string to run through PECOTA BATTING PROJECTIONS
req2 = requests.get("http://lookup-service-prod.mlb.com/json/named.proj_pecota_batting.bam?season='2018'&player_id='" + str(playerId) + "'")
info1 = req2.json()['proj_pecota_batting']['queryResults']['row']
# KEYS
hr = info1['hr']
sac = info1['sac']
rbi = info1['rbi']
tb = info1['tb']
slg = info1['slg']
bavg = info1['avg']
bb = info1['bb']
ops = info1['ops']
hbp = info1['hbp']
games = info1['g']
d = info1['d']
e = info1['e']
so = info1['so']
sf = info1['sf']
tpa = info1['tpa']
h = info1['h']
cs = info1['cs']
obp = info1['obp']
t = info1['t']
s = info1['s']
r = info1['r']
sb = info1['sb']
sbpct = info1['sbpct']
ab = info1['ab']
ibb = info1['ibb']
print(player,team,hr,sac,rbi,tb,slg,bavg,bb,ops,hbp,games,d,e,so,sf,tpa,h,cs,obp,t,s,r,sb,sbpct,ab,ibb)
Если я добавлю try:
except(KeyError):
Это будет работать, нопропускает много игроков в процессе, как примеры, которые я использовал ранее.Что не имеет смысла для меня, потому что, если они работали до try
, почему бы не сейчас?Копирование только отредактированной части сценария ниже, чтобы показать try:
except:
.
РЕДАКТИРОВАТЬ СКРИПТ:
# Use playerId string to run through PECOTA BATTING PROJECTIONS
req2 = requests.get("http://lookup-service-prod.mlb.com/json/named.proj_pecota_batting.bam?season='2018'&player_id='" + str(playerId) + "'")
try:
info1 = req2.json()['proj_pecota_batting']['queryResults']['row']
except(KeyError):
# KEYS
hr = info1['hr']
sac = info1['sac']
rbi = info1['rbi']
tb = info1['tb']
slg = info1['slg']
bavg = info1['avg']
bb = info1['bb']
ops = info1['ops']
hbp = info1['hbp']
games = info1['g']
d = info1['d']
e = info1['e']
so = info1['so']
sf = info1['sf']
tpa = info1['tpa']
h = info1['h']
cs = info1['cs']
obp = info1['obp']
t = info1['t']
s = info1['s']
r = info1['r']
sb = info1['sb']
sbpct = info1['sbpct']
ab = info1['ab']
ibb = info1['ibb']
print(player,team,hr,sac,rbi,tb,slg,bavg,bb,ops,hbp,games,d,e,so,sf,tpa,h,cs,obp,t,s,r,sb,sbpct,ab,ibb)