-
Notifications
You must be signed in to change notification settings - Fork 1
/
electsys_assistance.py.bak
302 lines (269 loc) · 9.93 KB
/
electsys_assistance.py.bak
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
#! python2
# -*- coding=utf-8 -*-
from splinter.browser import Browser
from time import sleep
from os import system
import os
import logging
import sys
import queue
import threading
import urllib.request, urllib.error, urllib.parse
from PIL import Image
import pytesseract
class NeedRelogin(Exception):
def __str__(self):
return 'need_relogin'
login_page = "http://electsys.sjtu.edu.cn/edu/"
select_page = "http://electsys.sjtu.edu.cn/edu/student/elect/warning.aspx?&xklc=%d&lb=%d"
restart_after = 0
user_name = ''
password = ''
nth_round_text = ['一专海选', '一专抢选', '一专第三轮', '暑假小学期海选', '暑假小学期抢选', '暑假小学期第3轮', '二专抢选', '二专重修']
parameter = {}
lesson_type_text = ['必修课', '限选课', '通识课', '任选课', '新生研讨课']
select_page_parameter = [(1, 1), (2, 1), (3, 1), (1, 3), (2, 3), (3, 3), (4, 2), (5, 2)]
queue = queue.Queue()
no_response = False
class ReloadThread(threading.Thread):
def __init__(self):
super(ReloadThread, self).__init__()
self.restart = False
def run(self):
global browser
try:
# print 'restart', self.restart
if restart:
try:
browser.quit()
except:
pass
browser = Browser('chrome')
else:
browser.reload()
except Exception as e:
logging.getLogger().info('reload page falied')
logging.getLogger().info(str(e))
else:
logging.getLogger().info('reload page successfully')
class CheckThread(threading.Thread):
def __init__(self):
global no_response
super(CheckThread, self).__init__()
self.continue_reload_time = 0
no_response = False
def run(self):
global no_response
while True:
# print 'no_response', no_response
if no_response:
self.continue_reload_time += 1
t = ReloadThread()
t.restart = (self.continue_reload_time > 3)
print(t.restart)
t.setDaemon(True)
t.run()
else:
self.continue_reload_time = 0
no_response = True
sleep(20)
def initLogger():
logger = logging.getLogger()
logger.setLevel(logging.INFO)
ABSPATH = os.path.dirname(os.path.abspath(sys.argv[0]))
fh = logging.FileHandler('%s/electsys.log' % ABSPATH)
fh.setLevel(logging.INFO)
fh.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
logger.addHandler(fh)
sh = logging.StreamHandler()
sh.setLevel(logging.INFO)
sh.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
logger.addHandler(sh)
def readConfig():
try:
fp = open('config.txt', 'r')
global user_name, password, restart_after
user_name = fp.readline().strip()
password = fp.readline().strip()
restart_after = int(fp.readline().strip())
if restart_after == -1:
restart_after = 1000000
elif restart_after == 0:
restart_after = 60
elif restart_after < -1:
raise Exception()
for line in fp:
if line.strip != '':
content = line.split()
dic = {
'nth_round': int(content[0]) - 1,
'lesson_type': int(content[1]) - 1,
'radio_num': int(content[2]) - 1,
'grade_num': content[3],
'lesson_code': content[4],
'teacher_num': int(content[5]) - 1
}
queue.put(dic)
except Exception as e:
logging.getLogger().info("load config failed.")
logging.getLogger().info(str(e))
raise e
else:
logging.getLogger().info("load config successfully")
def getCaptcha(cookie):
captcha_url = 'https://jaccount.sjtu.edu.cn/jaccount/captcha'
req = urllib.request.Request(captcha_url, headers={'cookie': cookie})
res = urllib.request.urlopen(req)
fp = open('captcha.jpg', 'wb')
fp.write(res.read())
fp.close()
image = Image.open('captcha.jpg')
image.load()
captcha = pytesseract.image_to_string(image)
return captcha
def login():
global browser, no_response
no_response = False
try:
browser.visit(login_page)
browser.find_link_by_href('login.aspx').click()
while 'jaccount' in browser.url:
cookie = '; '.join([('%s=%s' % x) for x in list(browser.cookies.all().items())])
captcha = getCaptcha(cookie)
browser.fill('user', 'hnxxjyt')
browser.fill('pass', '******')
browser.fill('captcha', captcha)
browser.find_by_name('imageField').click()
except Exception as e:
logging.getLogger().info("%s login failed." % user_name)
logging.getLogger().info(str(e))
raise e
else:
logging.getLogger().info("%s login successfully" % user_name)
return
def selectRound(first_time):
global no_response
no_response = False
try:
browser.visit(select_page % select_page_parameter[parameter['nth_round']])
if ('message' in browser.url) or ('outTimePage' in browser.url):
raise NeedRelogin()
if browser.is_element_present_by_id('btnContinue'):
browser.find_by_id('CheckBox1').click()
browser.find_by_id('btnContinue').click()
except Exception as e:
logging.getLogger().info("select round %d failed." % (parameter['nth_round'] + 1))
logging.getLogger().info(str(e))
raise e
else:
logging.getLogger().info("select round %d successfully" % (parameter['nth_round'] + 1))
def selectLessonType():
global no_response
no_response = False
try:
browser.find_by_value(lesson_type_text[parameter['lesson_type']]).click()
except Exception as e:
logging.getLogger().info("select lesson type %d failed." % (parameter['lesson_type'] + 1))
logging.getLogger().info(str(e))
else:
logging.getLogger().info("select lesson type %d successfully" % (parameter['lesson_type'] + 1))
def selectLesson():
global no_response
no_response = False
try:
if parameter['lesson_type'] == 1 or parameter['lesson_type'] == 2:
browser.find_by_value('radioButton')[parameter['radio_num']].click()
elif parameter['lesson_type'] == 3:
school_select = browser.find_by_tag('select')[0]
school_select.click()
school_select.find_by_tag('option')[parameter['radio_num']].click()
grade_select = browser.find_by_tag('select')[1]
grade_select.click()
grade_select.find_by_value(parameter['grade_num']).click()
browser.find_by_value('查 询').click()
if(browser.find_by_value(parameter['lesson_code'])):
browser.find_by_value(parameter['lesson_code'])[0].click()
browser.find_by_value('课程安排').click()
except Exception as e:
logging.getLogger().info("check lesson %s failed." % parameter['lesson_code'])
logging.getLogger().info(str(e))
raise e
else:
logging.getLogger().info("check lesson %s successfully" % parameter['lesson_code'])
def selectTeacher():
global no_response
no_response = False
try:
teacher_list = browser.find_by_name('myradiogroup')
if not teacher_list[parameter['teacher_num']].checked:
teacher_list[parameter['teacher_num']].click()
browser.find_by_value('选定此教师').click()
if 'message' in browser.url:
raise Exception()
browser.find_by_value('选课提交').click()
else:
logging.getLogger().info("lesson %s has been choosed" % parameter['lesson_code'])
return True
except Exception as e:
logging.getLogger().info("select teacher %d failed." % (parameter['teacher_num'] + 1))
logging.getLogger().info(str(e))
raise e
else:
logging.getLogger().info("select teacher %d successfully" % (parameter['teacher_num'] + 1))
return False
def main():
t = CheckThread()
t.setDaemon(True)
t.start()
readConfig()
global browser, no_response
# browser = Browser(driver)
while not queue.empty():
try:
login()
except Exception as e:
continue
for i in range(restart_after):
global parameter
if queue.empty():
return
parameter = queue.get()
try:
selectRound(i == 0)
selectLessonType()
selectLesson()
if not selectTeacher():
queue.put(parameter)
else:
logging.getLogger().info("select lesson %s successfully!!!!!" % parameter['lesson_code'])
except Exception as e:
queue.put(parameter)
if isinstance(e, NeedRelogin):
logging.getLogger().info('Sorry, I have to relogin. Please wait for 30 seconds...')
for i in range(30):
no_response = False
sleep(1)
break
no_response = False
# sleep(1)
try:
browser.quit()
except:
pass
browser = Browser(driver)
if __name__ == '__main__':
initLogger()
driver = 'firefox'
try:
browser = Browser('fi1refox')
except:
try:
browser = Browser('chrome')
except:
logging.getLogger().fatal('No browser driver!!! Please make sure that \'chromedriver.exe\' does exist.')
exit(0)
driver = 'chrome'
main()
logging.getLogger().info('All lessons have been chosen successfully, congratulations!!!')
browser.quit()
system('PAUSE')