def exam_handler(cookies, xnxqid, output_dir='.'): auth = Auth(cookies) url = 'https://jwxt.sztu.edu.cn/jsxsd/xsks/xsksap_list' r = auth.post(url, data={'xnxqid': xnxqid}) print(r.text) soup = BeautifulSoup(r.text, features='html.parser') tables = soup.findAll('table') if len(tables) < 1: raise Exception('未查询到考试安排') tab = tables[0] schedules = [] for tr in tab.findAll('tr'): if tr.findAll('td'): exam = tr.findAll('td') origDayTimeText = exam[6].getText().split(' ') day = origDayTimeText[0] origTimeText = origDayTimeText[1].split('~') startTime = origTimeText[0] endTime = origTimeText[1] print(day, startTime, endTime) tmp = { 'name': exam[4].getText(), 'day': day, 'startTime': startTime, 'endTime': endTime, 'location': exam[7].getText() } print(tmp) schedules.append(tmp) print("---------------------------") # 创建 ics ics = "%s/%s-exam.ics" % (output_dir, xnxqid) f = open(ics, 'w', encoding='utf-8') f.write(u'BEGIN:VCALENDAR\nVERSION:2.0\n') for exam in schedules: message = ''' BEGIN:VEVENT SUMMARY:%s DTSTART;TZID="UTC+08:00";VALUE=DATE-TIME:%sT%s DTEND;TZID="UTC+08:00";VALUE=DATE-TIME:%sT%s LOCATION:%s END:VEVENT\n''' % (exam['name'], exam['day'].replace( '-', ''), exam['startTime'].replace(':', '') + "00", exam['day'].replace('-', ''), exam['endTime'].replace(':', '') + "00", exam['location']) print(message) f.write(message) f.write(u'END:VCALENDAR') f.close() return ics
def get_major_list(cookies, college_id, grade): auth = Auth(cookies) r = auth.get( 'https://jwxt.sztu.edu.cn/jsxsd/kbcx/getZyByAjax?&skyx=%s&sknj=%s' % (college_id, grade)) r = json.loads(r.text) res = {} for m in r: res[m['dm']] = m['dm_mc'] return res
def login(): request_body = request.json auth = Auth() cookies, ok = auth.login(request_body['school_id'], request_body['password']) if ok: return {"cookies": cookies} else: return { "error": "登录失败,学号或密码错误", }, 403
def get_semester(cookies): auth = Auth(cookies) r = auth.get('https://jwxt.sztu.edu.cn/jsxsd/xskb/xskb_list.do') soup = BeautifulSoup(r.text, features='html.parser') options = soup.find('select', id='xnxq01id') # [<option selected="selected" value="2021-2022-1">2021-2022-1</option>] selected = options.findAll('option', attrs={'selected': 'selected'})[0].getText() options = options.findAll('option') semester = [] for option in options: semester.append(option.getText()) return semester, selected
def get_college_and_grade_list(cookies): auth = Auth(cookies) r = auth.get('https://jwxt.sztu.edu.cn/jsxsd/kbcx/kbxx_xzb') soup = BeautifulSoup(r.text, features='html.parser') options = soup.find('select', id='skyx') options = options.findAll('option') college_list = {} for option in options: college_list[option['value']] = option.getText() options = soup.find('select', id='sknj') options = options.findAll('option') grade_list = [] for option in options: grade_list.append(option.getText()) return college_list, grade_list
def transposition(cookies, output, xnxq, college_id, grade, major_id): auth = Auth(cookies) data = { 'xnxqh': xnxq, 'kbjcmsid': 'EB5693B95B204102B2E28C5624C6E9ED', 'skyx': college_id, 'sknj': grade, 'skzy': major_id } r = auth.post('https://jwxt.sztu.edu.cn/jsxsd/kbcx/kbxx_xzb_ifr', data) soup = BeautifulSoup(r.text, features='html.parser') tab = soup.findAll('table')[0] # print(len(tab.findAll('tr'))) tr = tab.findAll('tr') # 定义 excel 操作句柄 path = os.path.join(output, '课表.xlsx') o = xlsxwriter.Workbook(path) workfomat = o.add_format({ 'align': 'center', 'valign': 'vcenter', 'text_wrap': True, }) for i in range(2, len(tr)): # print(tr[i]) td = tr[i].findAll('td') cnt = 0 _class = td[0].findAll('nobr')[0].text print(_class) e = o.add_worksheet(u'班级' + str(_class)) week = tr[0].findAll('th') # 星期几 for j in range(1, 8): print(week[j].text) e.write(0, j, week[j].text, workfomat) # 节次 section = tr[1].findAll('td') for j in range(1, 7): print(section[j].text) e.write(j, 0, section[j].text, workfomat) # 具体课程 for j in range(1, len(td) - 1): course_info = td[j].findAll('div', class_='kbcontent1') if len(course_info) > 0: course_info = str(course_info[0]).replace( '<div class="kbcontent1" id="">', '') course_info = str(course_info).replace('</div>', '') course_info = str(course_info).replace('<br/>', '\n') print(course_info) else: course_info = "此时间段无课程" print("此时间段无课程") day = int(cnt / 6) section = cnt % 6 e.set_column(1, day + 1, 30) e.write(section + 1, day + 1, course_info, workfomat) print(day, section) print("==============") cnt = cnt + 1 # 关闭 & 保存 o.close() return path
def course_excel_handler(cookies, xnxqid, start_date, output_dir='.'): auth = Auth(cookies) if not auth.ok: raise Exception('登录失败,请检查用户名密码') url = 'https://jwxt.sztu.edu.cn/jsxsd/xskb/xskb_print.do?' \ 'xnxq01id=%s&zc=&kbjcmsid=EB5693B95B204102B2E28C5624C6E9ED&wkbkc=1' % xnxqid start_date = start_date.split('-') r = auth.get_excel(url) schedules = [] with tempfile.TemporaryDirectory() as temp_dir: path = os.path.join(temp_dir, 'course_excel.xls') excel_file = open(path, 'wb') excel_file.write(r.content) excel_file.close() workbook = xlrd.open_workbook(path) sheet = workbook.sheet_by_index(0) for i in range(3, 9): for j in range(1, 8): value = sheet.cell(i, j).value value = value.strip() # 多节课占用同一时间段 value = value.split('\n\n') for k in range(len(value)): value[k] = value[k].split('\n') if value[k][0] == '': continue # 汽车课表: [['智能汽车标定技术', '王永辉', '1-18([周])[09-10-11节]', 'C-5-219']] if str(value[k][2]).find('([周])') > 0 and str(value[k][2]).find('节') > 0: _index = 2 else: _index = 3 print(value[k][_index]) zc, section = handle_zc(value[k][_index]) tmp = { 'name': value[k][0], 'week': zc, 'section_index': section, 'location': value[k][_index + 1], 'description': value[k][_index - 1], 'day': j - 1, } schedules.append(tmp) print('第%s节,周%s %s' % (i - 2, j, value)) print() # 只是一个简单的换行 # 去重 _schedules = [] for item in schedules: if item not in _schedules: _schedules.append(item) schedules = _schedules print(schedules) # 创建 ics ics = "%s/%s.ics" % (output_dir, xnxqid) message = '' f = open(ics, 'w', encoding='utf-8') f.write(u'BEGIN:VCALENDAR\nVERSION:2.0\n') for course in schedules: start = datetime.datetime(int(start_date[0]), int(start_date[1]), int(start_date[2])) date = start - datetime.timedelta(start.weekday()) hour = timetable.translate(course['section_index']) for w in course['week']: day = (date + datetime.timedelta(days=course['day'] + 7 * (int(w) - 1))) if day < start: continue # 如本来周六有课,但是被假期的补课冲掉了 if holiday.is_markup_day(date.strftime('%Y-%m-%d')): continue # 处理假期及补课 if holiday.is_holiday(day.strftime('%Y-%m-%d')): m = holiday.makeup(day.strftime('%Y-%m-%d')) if m: day = m else: continue day = day.strftime('%Y%m%d') message += ''' BEGIN:VEVENT SUMMARY:%s DTSTART;TZID="UTC+08:00";VALUE=DATE-TIME:%sT%s DTEND;TZID="UTC+08:00";VALUE=DATE-TIME:%sT%s LOCATION:%s DESCRIPTION:%s END:VEVENT ''' % (course['name'], day, hour[0], day, hour[1], course['location'], course['description']) print(message) f.write(message) f.write(u'END:VCALENDAR') f.close() return ics
def check_user(): cookies = request.headers.get('Q-COOKIES') cookies = json.loads(cookies) auth = Auth(cookies) auth.check_login() return {"success": auth.ok}
from config import config from course import course_handler from exam import exam_handler from auth2 import Auth parser = argparse.ArgumentParser(description='Project Qi CLi') parser.add_argument('-c', '--course', action="store_true", help='get course ics') parser.add_argument('-e', '--exam', action="store_true", help='get exam ics') args = parser.parse_args() school_id = config.get('user', 'name') pwd = config.get('user', 'password') xnxqid = config.get('core', 'xnxqid') start_date = config.get('core', 'start_date') auth = Auth() cookies, ok = auth.login(school_id, pwd) if not ok: print('login fail') exit() if args.course: course_handler(cookies, xnxqid, start_date) elif args.exam: exam_handler(cookies, xnxqid) else: print('args error')
def course_handler(cookies, xnxqid, start_date, output_dir='.'): auth = Auth(cookies) if not auth.ok: raise Exception('登录失败,请检查用户名密码') url = 'https://jwxt.sztu.edu.cn/jsxsd/xskb/xskb_list.do?xnxq01id=' + xnxqid start_date = start_date.split('-') r = auth.get(url) soup = BeautifulSoup(r.text, features='html.parser') tab = soup.findAll('table')[0] i = 0 schedules = [] for tr in tab.findAll('tr'): if tr.getText(): day = 0 for td in tr.findAll('td'): # 过滤掉备注 if '节' in td.getText(): # print(td) # 处理多节课占用同一时间段 td = str(td.find('div', class_='kbcontent')).replace( '<br/>-----------<br/>', '</div><div class="kbcontent">') # print(td) td = BeautifulSoup(td, features='html.parser') courses = td.find_all('div', class_='kbcontent') # print(courses) # print('星期%s' % str(day + 1)) for course in courses: # 课程名称 course_name = course.contents[0] print(course_name) # 周次 zc = course.find('font', title='周次(节次)').getText() # f**k 1-18双周 ds = 0 # 不处理 if '单' in zc: ds = 1 elif '双' in zc: ds = 2 # 节次 zc = zc.replace('节', '') section = re.findall(r'[\[](.+?)[]]', zc)[0] zc = zc.split('[')[0] # 去除中文 周次里的 1-18(周) 单 双 zc = re.sub('[\u4e00-\u9fa5]', '', zc).replace('()', '') _s = [] # 8,10,12,14,16 / 1-7,8-18 if ',' in zc: zc = zc.split(',') for s in zc: if '-' in s: w_range = s.split('-') print(w_range) _s += list( range(int(w_range[0]), int(w_range[1]) + 1)) else: _s.append(int(s)) else: # 1-18 if '-' in zc: # print(zc) zc = zc.split('-') # 1-18双周 zc_all = range(int(zc[0]), int(zc[1]) + 1) s_tmp = [] if ds != 0: if ds == 2: for _zc in zc_all: if _zc % 2 == 0: s_tmp += [_zc] elif ds == 1: for _zc in zc_all: if _zc % 2: s_tmp += [_zc] _s = s_tmp else: _s = list(zc_all) # 2019-2020-1, 6 else: _s += [int(zc)] # print('周次: %s' % _s) # 教室 classroom = course.find('font', title='教室').getText() # print(classroom) # 教室 if '-' in section: section = section.split('-') _tmp = [] for s in section: _tmp += [int(s)] section = _tmp else: section = [int(section)] # print('节次:%s' % str(section)) # print('教室: %s' % classroom) # print('==================') tmp = { 'name': course_name, 'day': day, 'week': _s, 'section_index': section, 'location': classroom } schedules += [tmp] # 统计节数 i += 1 day += 1 # 去重 _schedules = [] for item in schedules: if item not in _schedules: _schedules.append(item) schedules = _schedules print('课程总数:%s' % i) print(schedules) # 创建 ics ics = "%s/%s.ics" % (output_dir, xnxqid) message = '' f = open(ics, 'w', encoding='utf-8') f.write(u'BEGIN:VCALENDAR\nVERSION:2.0\n') for course in schedules: start = datetime.datetime(int(start_date[0]), int(start_date[1]), int(start_date[2])) date = start - datetime.timedelta(start.weekday()) hour = timetable.translate(course['section_index']) for w in course['week']: day = (date + datetime.timedelta(days=course['day'] + 7 * (int(w) - 1))) if day < start: continue # 处理假期及补课 if holiday.is_holiday(day.strftime('%Y-%m-%d')): m = holiday.makeup(day.strftime('%Y-%m-%d')) if m: day = m else: continue day = day.strftime('%Y%m%d') message += '''BEGIN:VEVENT SUMMARY:%s DTSTART;TZID="UTC+08:00";VALUE=DATE-TIME:%sT%s DTEND;TZID="UTC+08:00";VALUE=DATE-TIME:%sT%s LOCATION:%s END:VEVENT ''' % (course['name'], day, hour[0], day, hour[1], course['location']) print(message) f.write(message) f.write(u'END:VCALENDAR') f.close() return ics