-
Notifications
You must be signed in to change notification settings - Fork 6
/
profiles.go
303 lines (261 loc) · 7.39 KB
/
profiles.go
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
/*
This file contains the code for the professor profile scraper.
*/
package scrapers
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"os"
"regexp"
"strconv"
"strings"
"github.com/UTDNebula/api-tools/utils"
"github.com/UTDNebula/nebula-api/api/schema"
"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/runtime"
"github.com/chromedp/chromedp"
"go.mongodb.org/mongo-driver/bson/primitive"
)
const BASE_URL string = "https://profiles.utdallas.edu/browse?page="
var primaryLocationRegex *regexp.Regexp = regexp.MustCompile(`^(\w+)\s+(\d+\.\d{3}[A-z]?)$`)
var fallbackLocationRegex *regexp.Regexp = regexp.MustCompile(`^([A-z]+)(\d+)\.?(\d{3}[A-z]?)$`)
func parseLocation(text string) schema.Location {
var building string
var room string
submatches := primaryLocationRegex.FindStringSubmatch(text)
if submatches == nil {
submatches = fallbackLocationRegex.FindStringSubmatch(text)
if submatches == nil {
return schema.Location{}
} else {
building = submatches[1]
room = fmt.Sprintf("%s.%s", submatches[2], submatches[3])
}
} else {
building = submatches[1]
room = submatches[2]
}
return schema.Location{
Building: building,
Room: room,
Map_uri: fmt.Sprintf("https://locator.utdallas.edu/%s_%s", building, room),
}
}
func parseList(list []string) (string, schema.Location) {
var phoneNumber string
var office schema.Location
for _, element := range list {
element = strings.Trim(element, " ")
utils.VPrintf("Element is: %s", element)
if strings.Contains(element, "-") {
phoneNumber = element
} else if primaryLocationRegex.MatchString(element) || fallbackLocationRegex.MatchString(element) {
utils.VPrintf("Element match is: %s", element)
office = parseLocation(element)
break
}
}
return phoneNumber, office
}
func parseName(fullName string) (string, string) {
commaIndex := strings.Index(fullName, ",")
if commaIndex != -1 {
fullName = fullName[:commaIndex]
}
names := strings.Split(fullName, " ")
ultimateName := strings.ToLower(names[len(names)-1])
if len(names) > 2 && (ultimateName == "jr" ||
ultimateName == "sr" ||
ultimateName == "I" ||
ultimateName == "II" ||
ultimateName == "III") {
names = names[:len(names)-1]
}
return names[0], names[len(names)-1]
}
func getNodeText(node *cdp.Node) string {
if len(node.Children) == 0 {
return ""
}
return node.Children[0].NodeValue
}
func scrapeProfessorLinks(chromedpCtx context.Context) []string {
var pageLinks []*cdp.Node
_, err := chromedp.RunResponse(chromedpCtx,
chromedp.Navigate(BASE_URL+"1"),
chromedp.QueryAfter(".page-link",
func(ctx context.Context, _ runtime.ExecutionContextID, nodes ...*cdp.Node) error {
pageLinks = nodes
return nil
},
),
)
if err != nil {
panic(err)
}
numPages, err := strconv.Atoi(getNodeText(pageLinks[len(pageLinks)-2]))
if err != nil {
panic(err)
}
professorLinks := make([]string, 0, numPages)
for curPage := 1; curPage <= numPages; curPage++ {
_, err := chromedp.RunResponse(chromedpCtx,
chromedp.Navigate(BASE_URL+strconv.Itoa(curPage)),
chromedp.QueryAfter("//h5[@class='card-title profile-name']//a",
func(ctx context.Context, _ runtime.ExecutionContextID, nodes ...*cdp.Node) error {
for _, node := range nodes {
href, hasHref := node.Attribute("href")
if !hasHref {
return errors.New("professor card was missing an href")
}
professorLinks = append(professorLinks, href)
}
return nil
},
),
)
if err != nil {
panic(err)
}
}
return professorLinks
}
func ScrapeProfiles(outDir string) {
chromedpCtx, cancel := initChromeDp()
defer cancel()
err := os.MkdirAll(outDir, 0777)
if err != nil {
panic(err)
}
var professors []schema.Professor
log.Print("Scraping professor links...")
professorLinks := scrapeProfessorLinks(chromedpCtx)
log.Print("Scraped professor links!")
for _, link := range professorLinks {
// Navigate to the link and get the names
var firstName, lastName string
utils.VPrint("Scraping name...")
_, err := chromedp.RunResponse(chromedpCtx,
chromedp.Navigate(link),
chromedp.ActionFunc(func(ctx context.Context) error {
var text string
err := chromedp.Text("//h2", &text).Do(ctx)
firstName, lastName = parseName(text)
return err
}),
)
if err != nil {
panic(err)
}
// Get the image uri
var imageUri string
utils.VPrint("Scraping imageUri...")
err = chromedp.Run(chromedpCtx,
chromedp.ActionFunc(func(ctx context.Context) error {
var attributes map[string]string
err := chromedp.Attributes("//img[@class='profile_photo']", &attributes, chromedp.AtLeast(0)).Do(ctx)
if err == nil {
var hasSrc bool
imageUri, hasSrc = attributes["src"]
if !hasSrc {
return errors.New("no src found for imageUri")
}
}
return err
}),
)
if err != nil {
err = chromedp.Run(chromedpCtx,
chromedp.ActionFunc(func(ctx context.Context) error {
var attributes map[string]string
err := chromedp.Attributes("//div[@class='profile-header fancy_header ']", &attributes, chromedp.AtLeast(0)).Do(ctx)
if err == nil {
var hasStyle bool
imageUri, hasStyle = attributes["style"]
if !hasStyle {
return errors.New("no style found for imageUri")
}
imageUri = imageUri[23 : len(imageUri)-3]
}
return err
}),
)
if err != nil {
panic(err)
}
}
// Get the titles
titles := make([]string, 0, 3)
utils.VPrint("Scraping titles...")
err = chromedp.Run(chromedpCtx,
chromedp.QueryAfter("//h6",
func(ctx context.Context, _ runtime.ExecutionContextID, nodes ...*cdp.Node) error {
for _, node := range nodes {
tempText := getNodeText(node)
if !strings.Contains(tempText, "$") {
titles = append(titles, tempText)
}
}
return nil
}, chromedp.AtLeast(0),
),
)
if err != nil {
continue
}
// Get the email
var email string
utils.VPrint("Scraping email...")
err = chromedp.Run(chromedpCtx,
chromedp.Text("//a[contains(@id,'☄️')]", &email, chromedp.AtLeast(0)),
)
if err != nil {
continue
}
// Get the phone number and office location
var texts []string
utils.VPrint("Scraping list text...")
err = chromedp.Run(chromedpCtx,
chromedp.QueryAfter("div.contact_info > div",
func(ctx context.Context, _ runtime.ExecutionContextID, nodes ...*cdp.Node) error {
var tempText string
err := chromedp.Text("div.contact_info > div", &tempText).Do(ctx)
texts = strings.Split(tempText, "")
return err
},
),
)
if err != nil {
panic(err)
}
utils.VPrint("Parsing list...")
phoneNumber, office := parseList(texts)
utils.VPrintf("Parsed list! #: %s, Office: %v", phoneNumber, office)
professors = append(professors, schema.Professor{
Id: schema.IdWrapper(primitive.NewObjectID().Hex()),
First_name: firstName,
Last_name: lastName,
Titles: titles,
Email: email,
Phone_number: phoneNumber,
Office: office,
Profile_uri: link,
Image_uri: imageUri,
Office_hours: []schema.Meeting{},
Sections: []schema.IdWrapper{},
})
utils.VPrintf("Scraped profile for %s %s!", firstName, lastName)
}
// Write professor data to output file
fptr, err := os.Create(fmt.Sprintf("%s/profiles.json", outDir))
if err != nil {
panic(err)
}
encoder := json.NewEncoder(fptr)
encoder.SetIndent("", "\t")
encoder.Encode(professors)
fptr.Close()
}