forked from okcd00/CDSelector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUCAS_Selector.py
222 lines (195 loc) · 8.77 KB
/
UCAS_Selector.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
#coding=utf8
# =====================================================
# Copyright (C) 2016 All rights reserved.
#
# filename : UCAS_Selector.py
# author : okcd00 / [email protected]
# refer : [email protected]
# date : 2017-01-11
# desc : UCAS Course_Selection Module
# =====================================================
import sys
import time
import requests
from configparser import RawConfigParser
from bs4 import BeautifulSoup
class UCAS_Selector:
def __init__(self):
self.__readCoursesId('./courseid')
cf = RawConfigParser()
cf.read('config')
self.username = cf.get('info', 'username')
self.password = cf.get('info', 'password')
self.runtime = cf.getint('info', 'runtime')
self.debug = cf.getboolean('action', 'debug')
self.enroll = cf.getboolean('action', 'enroll')
self.evaluate = cf.getboolean('action', 'evaluate')
self.select_bat = cf.getboolean('action', 'select_bat')
self.loginPage = 'http://sep.ucas.ac.cn'
self.loginUrl = self.loginPage + '/slogin'
self.courseSystem = self.loginPage + '/portal/site/226/821'
self.courseBase = 'http://jwxk.ucas.ac.cn'
self.courseIdentify = self.courseBase + '/login?Identity='
self.courseSelected = self.courseBase + '/courseManage/selectedCourse'
self.courseSelectionBase = self.courseBase + '/courseManage/main'
self.courseCategory = self.courseBase + '/courseManage/selectCourse?s='
self.courseSave = self.courseBase + '/courseManage/saveCourse?s='
self.studentCourseEvaluateUrl = 'http://jwjz.ucas.ac.cn/Student/DeskTopModules/'
self.selectCourseUrl = 'http://jwjz.ucas.ac.cn/Student/DesktopModules/Course/SelectCourse.aspx'
self.enrollCount = {}
self.headers = {
'Host': 'sep.ucas.ac.cn',
'Connection': 'keep-alive',
'Pragma': 'no-cache',
'Cache-Control': 'no-cache',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36',
'Accept-Encoding': 'gzip, deflate, sdch',
'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6',
}
self.s = requests.Session()
loginPage = self.s.get(self.loginPage, headers=self.headers)
self.cookies = loginPage.cookies
def login(self):
postdata = {
'userName': self.username,
'pwd': self.password,
'sb': 'sb'
}
self.s.post(self.loginUrl, data=postdata, headers=self.headers)
if 'sepuser' in self.s.cookies.get_dict():
return True
return False
def getMessage(self, restext):
css_soup = BeautifulSoup(restext, 'html.parser')
text = css_soup.select('#main-content > div > div.m-cbox.m-lgray > div.mc-body > div')[0].text
return "".join(line.strip() for line in text.split('\n'))
def __readCoursesId(self, filename):
coursesFile = open(filename, 'r')
self.coursesId = {}
for line in coursesFile.readlines():
line = line.strip().replace(' ', '').split(':')
courseId = line[0]
isDegree = False
if len(line) == 2 and line[1] == 'on':
isDegree = True
self.coursesId[courseId] = isDegree
def enrollCourses(self):
response = self.s.get(self.courseSystem, headers=self.headers)
soup = BeautifulSoup(response.text, 'html.parser')
try:
identity = str(soup).split('Identity=')[1].split('"'[0])[0]
coursePage = self.courseIdentify + identity
response = self.s.get(coursePage)
response = self.s.get(self.courseSelected)
idx, lastMsg = 0, ""
while True:
msg = ""
if self.select_bat:
# print self.coursesId
result, msg = self.__enrollCourses(self.coursesId)
if result: self.enrollCount[eachCourse] = 0
else:
for eachCourse in self.coursesId:
if eachCourse in response.text:
print("Course " + eachCourse + " has been selected.")
continue
if (eachCourse in self.enrollCount and
self.enrollCount[eachCourse] == 0):
continue
self.enrollCount[eachCourse] = 1
result = self.__enrollCourse(eachCourse, self.coursesId[eachCourse])
if result:
self.enrollCount[eachCourse] = 0
for enroll in self.enrollCount:
if self.enrollCount[enroll] == 0:
self.coursesId.pop(enroll)
self.enrollCount.clear()
if not self.coursesId: return
idx += 1
time.sleep(self.runtime)
showText = "\r> " + "%s <%d> %s" % (
msg if msg!=lastMsg else "", idx,
time.asctime( time.localtime(time.time()) )
)
lastMsg = msg
sys.stdout.write(showText)
sys.stdout.flush()
except KeyboardInterrupt:
print("Bye")
except Exception as exception:
print("System error")
print(exception)
exit()
def __enrollCourse(self, courseId, isDegree):
response = self.s.get(self.courseSelectionBase)
if debug:
print #(response.text.encode('utf-8'))
soup = BeautifulSoup(response.text, 'html.parser')
categories = dict([(label.contents[0][:2], label['for'][3:])
for label in soup.find_all('label')[2:]])
categoryId = categories[courseId[:2]]
identity = soup.form['action'].split('=')[1]
postdata = {
'deptIds': categoryId,
'sb': 0
}
categoryUrl = self.courseCategory + identity
response = self.s.post(categoryUrl, data=postdata)
if debug:
print #(response.text.encode('utf-8'))
soup = BeautifulSoup(response.text, 'html.parser')
courseTable = soup.body.form.table.find_all('tr')[1:]
courseDict = dict([(c.span.contents[0], c.span['id'].split('_')[1])
for c in courseTable])
if courseId in courseDict:
postdata = {
'deptIds': categoryId,
'sids': courseDict[courseId]
}
print categoryId
if isDegree:
postdata['did_' + courseDict[courseId]] = courseDict[courseId]
courseSaveUrl = self.courseSave + identity
response = self.s.post(courseSaveUrl, data=postdata)
if 'class="error' not in response.text:
print('[Success] ' + courseId)
return True
else: return False
else:
print("No such course")
return True
def __enrollCourses(self, courseIds): # For English
response = self.s.get(self.courseSelectionBase)
if debug: print #(response.text.encode('utf-8'))
soup = BeautifulSoup(response.text, 'html.parser')
categories = dict([(label.contents[0][:2], label['for'][3:])
for label in soup.find_all('label')[2:]])
identity = soup.form['action'].split('=')[1]
categoryIds = []
for courseId in courseIds:
categoryIds.append(categories[courseId[:2]])
postdata = {
'deptIds': categoryIds,
'sb': 0
}
categoryUrl = self.courseCategory + identity
response = self.s.post(categoryUrl, data=postdata)
if debug: print #(response.text.encode('utf-8'))
soup = BeautifulSoup(response.text, 'html.parser')
courseTable = soup.body.form.table.find_all('tr')[1:]
courseDict = dict([(c.span.contents[0], c.span['id'].split('_')[1])
for c in courseTable])
postdata = {
'deptIds': categoryIds,
'sids': [courseDict[courseId] for courseId in courseIds]
}
courseSaveUrl = self.courseSave + identity
response = self.s.post(courseSaveUrl, data=postdata)
with open('result.html','wb+') as f:
f.write(response.text.encode('utf-8'))
if 'class="error' not in response.text:
print('[Success] ' + courseId)
return True, "Success!"
else: return False, self.getMessage(response.text).strip()