-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathncaa_hoops_scraper.R
176 lines (147 loc) · 6.35 KB
/
ncaa_hoops_scraper.R
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
### Adapted from a file produced by Prof. Jay Emerson used in
### Introductory Data Analysis (STAT 230), Spring 2016
library(dplyr)
# Stripwhite function
stripwhite <- function(x) gsub("\\s*$", "", gsub("^\\s*", "", x))
### Fix
fix_team <- function(x) {
possible_fix <- teamid$team[sapply(teamid$team, grepl, x)]
return(possible_fix[nchar(possible_fix) == max(nchar(possible_fix))])
}
### Read in ID's table
teamid <-
read.csv("3.0_Files/Info/conferences.csv", as.is = T) %>%
select(team, ncaa_id, conference) %>%
arrange(team)
################################################################################
baseurl <- 'https://stats.ncaa.org/teams/'
tournaments <- c('Empire Classic (Riverside)', 'Myrtle Beach Invitational',
'Maui Invitational (Mainland)', 'Cayman Islands (Mainland)',
"- MBB Negro League Baseball Museum Tipoff Classic",
'Hawaiian Airlines Diamond Head Classic',
"- MBB Penguin Classic",
'MBB Roadrunner Invitational',
'- MBB Don Haskins Basketball Invitational,
')
conf_tournaments <- paste0('-\\sMBB\\s+', c("Big South", "Patriot League", "Northeast Conference",
"NEC", "Horizon League", "Mountain West", "ASUN", "MAC", "WCC",
'Patriot League',
"America East", "Sun Belt", "SWAC", "MEAC", "Big East",
"Big 10", "Big 12", "ACC", "SEC", "Ivy League"), "\\s+(Championship)+")
z <- NULL
bad <- NULL
for (i in 1:nrow(teamid)) {
cat("Getting", i, teamid$team[i], "\n")
# Elegantly scan and handle hiccups:
ct <- 0
while (ct >= 0 && ct <= 5) {
x <- try(readr::read_lines(paste(baseurl, teamid$ncaa_id[i], sep="")))
if (class(x) != "try-error") {
ct <- -1
} else {
warning(paste(ct, "try(scan) failed, retrying team ID",
teamid$id[i], "\n"))
Sys.sleep(0.5)
ct <- ct + 1
if (ct > 5) {
warning("Big internet problem")
bad <- c(bad, teamid$ncaa_id[i])
}
}
}
if (ct <= 5) { ### UMES cancelled
x <- x[-grep("^\\s*$", x)] # Drop lines with only whitespace
# Which lines contain dates surrounded immediately by > ... < ?
datelines <- grep("\\d\\d/\\d\\d/\\d\\d\\d\\d", x)
dates <- stripwhite(gsub("<[^<>]*>", "", x[datelines]))
dates <- gsub("\\(.*", "", gsub(" .*", "", dates))
ix <- !grepl("(Start|Team|End)", dates)
if(sum(ix) > 0) {
datelines <- datelines[ix]
dates <- dates[ix]
dates <- stringr::str_extract(dates, '\\d\\d/\\d\\d/\\d\\d\\d\\d')
ix2 <- !duplicated(dates)
dates <- dates[ix2]
dates <- matrix(as.numeric(unlist(strsplit(dates, "/"))),
ncol=3, byrow=TRUE)
opploc <- stripwhite(gsub("<[^<>]*>", "", x[datelines+2]))
loc <- rep("H", length(opploc))
loc[grep("@", opploc, fixed=TRUE)] <- "N"
loc[grep("^@", opploc)] <- "V"
opp <- opploc
opp[loc == "V"] <- gsub("@", "", gsub("@ ", "", opp[loc == "V"]))
opp[loc == "N"] <- substring(opp, 1, regexpr("@", opp)-2)[loc == "N"]
result <- stripwhite(gsub("<[^<>]*>", "", x[datelines+5]))
OT <- suppressWarnings(as.numeric(gsub("^.*\\((\\d)OT\\)",
"\\1", result))) # warnings okay
result <- gsub(" \\(.*\\)", "", result)
canceled <- result == 'Canceled'
postponed <- result == 'Postponed' | result == 'Ppd'
result[canceled|postponed] <- ""
result <- strsplit(substring(result, 3, 20), "-")
if (any(sapply(result, length) == 0)) {
result[sapply(result, length) == 0] <- list(c(NA, NA))
}
result <- matrix(as.numeric(unlist(result)), ncol=2, byrow=TRUE)
ixR <- 1:nrow(result)
if(length(ixR) == length(ix2)) {
ixR <- ix2
}
res <- data.frame(year=dates[,3],
month=dates[,1],
day=dates[,2],
team=teamid$team[i],
opponent=opp[ix2],
location=loc[ix2],
teamscore=result[ixR,1],
oppscore=result[ixR,2],
canceled=canceled[ix2],
postponed=postponed[ix2],
OT=OT[ix2], stringsAsFactors=FALSE)
res$date <- paste(res$month, res$day, sep = "_")
res$opponent <- stripwhite(gsub("&", "&", gsub("&x;", "'", gsub("[0-9]", "", gsub("#", "", res$opponent)))))
#fix <- sapply(res$opponent, function(x) { any(sapply(teamid$team, grepl, x)) }) &
# !res$opponent %in% teamid$team
#res$opponent[fix] <- sapply(res$opponent[fix], fix_team)
for(tourney in tournaments) {
res$opponent <- stripwhite(gsub(tourney, "", res$opponent))
}
for(tourney in conf_tournaments) {
res$opponent <- stripwhite(gsub(tourney, "", res$opponent))
}
res$opponent <- stripwhite(gsub('-?\\s+MBB.*$', '', res$opponent))
# Fix non-unique dates problem
uni_dates <- unique(res$date)
z <- rbind(z, res[uni_dates %in% res$date, -ncol(res)])
}
}
}
# Extract D1 Games
# rows <- strsplit(z$opponent[grep("@", z$opponent)], "@")
# if(length(rows) > 1) {
# for (i in 1:length(z$opponent[grep("@", z$opponent)])) {
# z$opponent[grep("@", z$opponent)][1] <- rows[[i]][1]
# }
# }
z <-
z %>%
mutate('opponent' = case_when(
# opponent == 'App State' ~ 'Appalachian St.',
# opponent == 'Nicholls' ~ "Nicholls St.",
# opponent == 'Sam Houston' ~ "Sam Houston St.",
opponent == 'Northern Ill.' ~ 'NIU',
opponent == 'FDU' ~ 'Fairleigh Dickinson',
opponent == 'East Texas A&M' ~ 'Tex. A&M-Commerce',
opponent == 'Saint Francis' ~ 'Saint Francis (PA)',
grepl('&;', opponent) ~ gsub('&;', "'", opponent),
T ~ opponent))
z$opponent <- stripwhite(z$opponent)
z$D1 <- z$team %in% teamid$team + z$opponent %in% teamid$team
# Get date materials
today <- unclass(as.POSIXlt(Sys.time()))
year <- 1900 + today$year
month <- 1 + today$mon
day <- today$mday
### Save Results
write.csv(z, paste("3.0_Files/Results/2024-25/NCAA_Hoops_Results_", month, "_",
day, "_", year, ".csv", sep=""), row.names = F)