Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathscrape_advanced.py
More file actions
Latest commit
302 lines (235 loc) · 9.08 KB
/
Copy pathscrape_advanced.py
File metadata and controls
302 lines (235 loc) · 9.08 KB
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
importsys
fromosimportmakedirs, rename, remove
fromos.pathimportjoin, exists
fromcollectionsimportdefaultdict
fromitertoolsimportproduct
importre
# 3rd party
importrequests
frombs4importBeautifulSoup
fromtinydbimportTinyDB
fromcoloramaimportinit, Fore, Style
fromsettingsimportDB_DIR, SSB_URL
fromemulate_loginimportlogin
CAMPUS_RANGE= (1, 2)
YEAR_RANGE= (1, 8)
QUARTER_RANGE= (1, 4)
DEBUG=True
PREFIXES= ('old', 'debug')
ADVANCED_FORM_DATA= [
[
[('sel_subj', 'dummy'), ('sel_day', 'dummy'), ('sel_schd', 'dummy'),
('sel_insm', 'dummy'), ('sel_camp', 'dummy'), ('sel_levl', 'dummy'),
('sel_sess', 'dummy'), ('sel_instr', 'dummy'), ('sel_ptrm', 'dummy'),
('sel_attr', 'dummy')],
[('sel_crse', ''), ('sel_title', ''), ('sel_from_cred', ''),
('sel_to_cred', ''), ('sel_camp', '%'), ('sel_sess', '%'),
('sel_instr', '%'), ('sel_ptrm', '%'), ('begin_hh', '0'),
('begin_mi', '0'), ('begin_ap', 'a'), ('end_hh', '0'), ('end_mi', '0'),
('end_ap', 'a'), ('SUB_BTN', 'Section Search'), ('path', '1')]
],
[
[('sel_subj', 'dummy'), ('sel_day', 'dummy'), ('sel_schd', 'dummy'),
('sel_insm', 'dummy'), ('sel_camp', 'dummy'), ('sel_levl', 'dummy'),
('sel_sess', 'dummy'), ('sel_instr', 'dummy'), ('sel_ptrm', 'dummy'),
('sel_attr', 'dummy')],
[('sel_crse', ''), ('sel_title', ''), ('sel_schd', '%'),
('sel_from_cred', ''), ('sel_to_cred', ''), ('sel_camp', '%'),
('sel_instr', '%'), ('sel_sess', '%'), ('sel_ptrm', '%'),
('sel_attr', '%'), ('begin_hh', '0'), ('begin_mi', '0'),
('begin_ap', 'a'), ('end_hh', '0'), ('end_mi', '0'),
('end_ap', 'a'), ('SUB_BTN', 'Section Search'), ('path', '1')]
],
[
[('sel_subj', 'dummy'), ('sel_day', 'dummy'), ('sel_schd', 'dummy'),
('sel_insm', 'dummy'), ('sel_camp', 'dummy'), ('sel_levl', 'dummy'),
('sel_sess', 'dummy'), ('sel_instr', 'dummy'), ('sel_ptrm', 'dummy'),
('sel_attr', 'dummy')],
[('sel_crse', ''), ('sel_title', ''), ('sel_schd', '%'),
('sel_from_cred', ''), ('sel_to_cred', ''), ('sel_camp', '%'),
('sel_levl', '%'), ('sel_ptrm', '%'), ('sel_instr', '%'),
('sel_sess', '%'), ('sel_attr', '%'), ('begin_hh', '0'),
('begin_mi', '0'), ('begin_ap', 'a'), ('end_hh', '0'), ('end_mi', '0'),
('end_ap', 'a'), ('SUB_BTN', 'Section Search'), ('path', '1')]
]
]
defmain():
ifnotexists(DB_DIR):
makedirs(DB_DIR, exist_ok=True)
ifnotexists(join(DB_DIR, 'html')):
makedirs(join(DB_DIR, 'html'), exist_ok=True)
codes=generate_term_codes()
print_c(f'Loaded {color(Fore.CYAN, len(codes))} term codes\n')
prefix=PREFIXES[0] ifnotDEBUGelsePREFIXES[1]
ifDEBUG:
codes=codes[:5]
print_c(f'Scraping session cookie…\r')
session=requests.session()
login(session)
temp_path=join(DB_DIR, 'temp.json')
try:
fortermincodes:
print_c(f" [{term}] [{color(Fore.YELLOW, 'MINING…')}] Scraping…\r")
temp=TinyDB(temp_path)
dept_data=mine_dept_data(term, write=False)
print_c(f" [{term}] [{color(Fore.YELLOW, 'MINING…')}] "+
f"Parsing {len(dept_data)} departments…\r")
failed=False
foridx, variantinenumerate(ADVANCED_FORM_DATA):
content=mine_table_data(session, term, variant, dept_data, write=False)
ifadvanced_parse(content, db=temp, term=term):
break
elifidx==len(ADVANCED_FORM_DATA) -1:
failed=True
ifrename(temp_path, join(DB_DIR, f'{prefix}_{term}_database.json')):
remove(temp_path)
db=TinyDB(join(DB_DIR, f'{prefix}_{term}_database.json'))
num_courses=sum([len(db.table(t).all()) fortindb.tables()])
iffailed:
print_c(f" [{term}] [{color(Fore.RED, 'ERROR!!')}] Payload failed…\n")
else:
print_c(f" [{term}] [{color(Fore.GREEN, 'SUCCESS')}] Mined {num_courses} courses\n")
except (KeyboardInterrupt) ase:
print_c(f"{color(Fore.GREEN, e)}\n")
remove(temp_path)
defmine_dept_data(term, write=False):
'''
Mine dept data will grab the department IDs for a given quarter.
:param term: (str) the term to mine
:param write: (bool) write to file?
:return data (list(tuple)) the html body
'''
data= [('p_calling_proc', 'bwckschd.p_disp_dyn_sched'), ('p_term', f'{term}')]
res=requests.post(SSB_URL+'/PROD/bwckgens.p_proc_term_date', data=data)
res.raise_for_status()
ifwrite:
write_to_file(res, term)
soup=BeautifulSoup(res.content, "html5lib")
select=soup.find('select', {'id': 'subj_id'})
options=select.find_all('option')
data= [('sel_subj', o['value']) foroinoptions]
returndata
defmine_table_data(session, term, payload, dept_data, write=False):
'''
Mine will hit the database for foothill's class listings
:param session: (session) an instance of requests.session()
:param term: (str) the term to mine
:param payload: (str) data payload for request
:param dept_data: (str) department data payload
:param write: (bool) write to file?
:return res.content: (json) the html body
'''
data= [('rsts', 'dummy'), ('crn', 'dummy'), ('term_in', f'{term}')]
data.extend(payload[0])
ifDEBUG:
dept_data=dept_data[:1]
data.extend(dept_data)
data.extend(payload[1])
res=session.post(SSB_URL+'/PROD/bwskfcls.P_GetCrse_Advanced', data=data)
res.raise_for_status()
ifwrite:
write_to_file(res, term)
returnres.content
defadvanced_parse(content, db, term=''):
'''
Advanced parse takes the content from the request and then populates the database with the data
:param content: (html) The html containing the courses
:param db: (TinyDB) the current database
:return: None
'''
soup=BeautifulSoup(content, 'html5lib')
table_rows=None
try:
table=soup.find('table', {'class': 'datadisplaytable'})
table_rows=table.find_all('tr')
exceptAttributeErrorase:
returnFalse
table_headers=list()
start_idx=0
fori, trinenumerate(table_rows):
header_cols=tr.find_all('th', {'class': 'ddheader'})
forthinheader_cols:
table_headers.append(get_parsed_text(th))
iftable_headers:
start_idx=i
break
fortrintable_rows[start_idx:]:
parse_row(tr, table_headers, db)
returnTrue
defparse_row(tr, th, db):
try:
cols=tr.find_all('td', {'class': 'dddefault'})
ifcols:
s=defaultdict(lambda: defaultdict(list))
num_blank=0
fori, cinenumerate(cols):
a=c.find('a')
cols[i] =get_parsed_text(a) ifaelseget_parsed_text(cols[i])
ifcols[i].isspace():
num_blank+=1
ifnum_blank>len(cols) -num_blank:
raiseBlankRow
data=dict(zip(th, cols))
subject=data['Subj']
key=data['Crse']
crn=data['CRN']
s[key][crn].append(data)
j=dict(s)
db.table(f'{subject}').insert(j)
exceptBlankRow:
return
defgenerate_term_codes():
"""
This helper generates a list of term codes based on the ranges set by:
YEAR_RANGE, QUARTER_RANGE, CAMPUS_RANGE
:return: (list(str)) list of term codes
"""
i=range(YEAR_RANGE[0], YEAR_RANGE[1] +1)
j=range(QUARTER_RANGE[0], QUARTER_RANGE[1] +1)
k=range(CAMPUS_RANGE[0], CAMPUS_RANGE[1] +1)
codes= [f'201{x[0]}{x[1]}{x[2]}'forxinproduct(i, j, k)]
returncodes
classBlankRow(Exception):
pass
defget_parsed_text(tag):
"""
Regex that strips all html tags and their contents
:param tag: (str) inner contents of parent tag
:return: (str) isolated text
"""
text=tag.get_text()
p=re.compile(r'<.*?>')
returnp.sub('', text)
defprint_c(message):
"""
Clears last carriage returned line and writes a new one
:param message: (str)
:return: None
"""
sys.stdout.write('\x1b[2K')
sys.stdout.write(message)
sys.stdout.flush()
defcolor(c, word):
"""
Format template that inserts a color for a given word
:param c: (Color) Color to format to
:param word: (str) Word to format
:return: (str) Formatted String
"""
returnf'{c}{word}{Style.RESET_ALL}'
defwrite_to_file(res, term):
"""
Writes a bytestream to a nested file directory
:param res: response object
:param term: term code
:return: None
"""
withopen(f"{join(DB_DIR, 'html', term+'.html')}", "wb") asfile:
forchunkinres.iter_content(chunk_size=512):
ifnotchunk:
break
file.write(chunk)
file.flush()
if__name__=='__main__':
init() #colorama
main()