-
Notifications
You must be signed in to change notification settings - Fork 1
/
fetch_csvs.py
executable file
·284 lines (253 loc) · 8.34 KB
/
fetch_csvs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
#!/usr/bin/env python3
import argparse
import csv
import itertools
import multiprocessing
import os
import lxml.html
import requests
SEARCH_URL = "http://web1.ncaa.org/stats/StatsSrv/careersearch"
RECORDS_URL = "http://web1.ncaa.org/stats/exec/records"
TEAM_URL = "http://web1.ncaa.org/stats/StatsSrv/careerteam"
SCHOOL_CSV = "csv/ncaa_schools.csv"
SCRAPE_GAME_COLS = [
"opponent_name",
"game_date",
"score",
"opponent_score",
"location",
"neutral_site_location",
"game_length",
"attendence",
]
GAME_COLS = SCRAPE_GAME_COLS + [
"opponent_id",
"year",
"school_id",
]
SCRAPE_PLAYER_COLS = [
"player_name",
"class",
"season",
"position",
"height",
"g",
"fg_made",
"fg_attempts",
"fg_percent",
"3pt_made",
"3pt_attempts",
"3pt_percent",
"freethrows_made",
"freethrows_attempts",
"freethrows_percent",
"rebounds_num",
"rebounds_avg",
"assists_num",
"assists_avg",
"blocks_num",
"blocks_avg",
"steals_num",
"steals_avg",
"points_num",
"points_avg",
"turnovers",
"dd",
"td",
]
PLAYER_COLS = SCRAPE_PLAYER_COLS + [
"player_id",
"year",
"school_id",
]
def post_form(url, post_data=None):
headers = {
"user-agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, "
"like Gecko) Chrome/41.0.2228.0 Safari/537.36",
"referrer": url,
}
if post_data is not None:
res = requests.post(url, data=post_data, headers=headers)
else:
res = requests.get(url, headers=headers)
res.raise_for_status()
return lxml.html.document_fromstring(res.text)
def read_csv(csv_in):
with open(csv_in, "r") as f:
reader = csv.DictReader(f)
return list(reader)
def write_csv(csv_out, data, colnames):
os.makedirs(os.path.dirname(csv_out), exist_ok=True)
with open(csv_out, "w") as f:
writer = csv.DictWriter(f, fieldnames=colnames)
writer.writeheader()
for row in data:
writer.writerow(row)
def load_schools():
if not os.path.exists(SCHOOL_CSV):
get_schools()
return read_csv(SCHOOL_CSV)
def get_school_games(year, school):
print("%s/%s" % (year, school["school_name"]))
path = "csv/games/ncaa_games_%s_%s.csv" % (year, school["school_id"])
if not os.path.exists(path):
int_cols = [
"opponent_id",
"score",
"opponent_score",
"attendence",
"school_id",
]
try:
page = post_form(
RECORDS_URL,
{
"academicYear": str(year),
"orgId": school["school_id"],
"sportCode": "MBB",
},
)
except requests.exceptions.HTTPError:
# We can try again later
print("Failed to load %s/%s" % (year, school["school_name"]))
return []
rows = page.xpath("//form[@name='orgRecords']/table[2]/tr[position()>1]")
games = []
for row in rows:
game = {
"school_id": school["school_id"],
"year": year,
}
for colname, cell in zip(SCRAPE_GAME_COLS, row.iterchildren()):
content = cell.text_content().strip()
if colname == "opponent_name":
content = content.replace("%", "").strip()
link = cell.xpath("a")
if link:
href = link[0].get("href")
_, end = href.split("(")
game["opponent_id"], _ = end.split(")")
else:
game["opponent_id"] = None
if content == "-":
content = None
elif colname == "attendence":
# remove commas
content = content.replace(",", "")
game[colname] = content
for colname in int_cols:
if colname in game and game[colname] is not None:
game[colname] = int(game[colname])
games.append(game)
write_csv(path, games, GAME_COLS)
return read_csv(path)
def get_games(years):
schools = load_schools()
for year in years:
path = "csv/ncaa_games_%s.csv" % year
if not os.path.exists(path):
games = []
for school in schools:
games.extend(get_school_games(year, school))
write_csv(path, games, GAME_COLS)
def get_school_players(year, school):
print("%s/%s" % (year, school["school_name"]))
path = "csv/players/ncaa_players_%s_%s.csv" % (year, school["school_id"])
if not os.path.exists(path):
int_cols = ["player_id", "height", "g"]
try:
page = post_form(
TEAM_URL,
{
"academicYear": str(year),
"orgId": school["school_id"],
"sportCode": "MBB",
"sortOn": "0",
"doWhat": "display",
"playerId": "-100",
"coachId": "-100",
"division": "1",
"idx": "",
},
)
except requests.exceptions.HTTPError:
# We can try again later
print("Failed to load %s/%s" % (year, school["school_name"]))
return []
rows = page.xpath("//table[@class='statstable'][2]//tr[position()>3]")
players = []
for row in rows:
player = {
"school_id": school["school_id"],
"year": year,
}
for colname, cell in zip(SCRAPE_PLAYER_COLS, row.iterchildren()):
content = cell.text_content().strip()
if colname == "player_name":
content = content.replace("%", "").strip()
link = cell.xpath("a")
if link:
href = link[0].get("href")
_, end = href.split("(")
id, _ = end.split(")")
if id == "-":
player["player_id"] = None
else:
player["player_id"] = id
else:
player["player_id"] = None
if content == "-":
content = None
elif colname == "height":
feet, inches = content.split("-")
content = int(feet) * 12 + int(inches)
player[colname] = content
for colname in int_cols:
if player[colname] is not None:
player[colname] = int(player[colname])
if player["player_name"] is not None:
players.append(player)
write_csv(path, players, PLAYER_COLS)
return read_csv(path)
def get_players(years):
schools = load_schools()
for year in years:
path = "csv/ncaa_players_%s.csv" % year
if not os.path.exists(path):
players = []
for school in schools:
players.extend(get_school_players(year, school))
write_csv(path, players, PLAYER_COLS)
def get_schools():
page = post_form(SEARCH_URL)
options = page.xpath("//select[@name='searchOrg']/option[position()>1]")
schools = [
{"school_id": option.get("value"), "school_name": option.text}
for option in options
]
write_csv(SCHOOL_CSV, schools, colnames=list(schools[0]))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest="command_name")
subparsers.required = True
commands = [
("get_games", get_games),
("get_players", get_players),
("get_schools", get_schools),
]
for name, func in commands:
subparser = subparsers.add_parser(name)
subparser.set_defaults(func=func)
if func != get_schools:
subparser.add_argument(
"--years",
"-y",
type=lambda v: map(int, v.split(",")),
default=list(range(2002, 2018)),
help="The years to scrape data for. (default: %(default)s",
)
args = parser.parse_args()
if args.func == get_schools:
args.func()
else:
args.func(args.years)