一、前言
源于EPC约考,每次开放名额很少,用脚本比在网页快的多。使用Python3,涉及requests和re模块。
second_id 的获取:
cookies 的获取:
二、代码
使用的是Jupyter
import requests
import time
import re
#############全局变量管理##################
second_id="xxxx"#个人id
baseURL="https://epc.ustc.edu.cn/"
# 伪造请求头
req_header = {
'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
'Content-Type': 'application/x-www-form-urlencoded'
}
#cookie 信息 从浏览器获得 该方法避免了 繁琐的 登录验证码识别
cookies_str="_ga=GA1.3.1307624726.1604932641; sduuid=4d3318d9dxxxx"
# 解析cookie
def SetCookies(cookies_str):
cookies={}
kv_list=cookies_str.split(';')
for kv in kv_list:
l=kv.split("=")
cookies[l[0]]=l[1]+";Path=/; Domain=.jw.ustc.edu.cn; "
return cookies
#获取 提交 链接
def getPostURL(weeks,days,second_id):
try:
chaxun_url="https://epc.ustc.edu.cn/m_service.asp?second_id="+second_id+"&week_day="+str(days)+"&week="+str(weeks)
response = requests.get(chaxun_url, headers=req_header,cookies=SetCookies(cookies_str))
if response.status_code==200:
patten='exam</td>\r\n\t\t\t\t\t\t\t\t\t<td align="center">(.*?)'#第几周
patten+='</td>\r\n\t\t\t\t\t\t\t\t\t<td align="center">(.*?)'#周几
patten+='</td>\r\n\t\t\t\t\t\t\t\t\t<td align="center">(.*?)'#考试时间
patten+='</td>\r\n\t\t\t\t\t\t\t\t\t<td align="center">(.*?)'#教室
patten+='</td>\r\n\t\t\t\t\t\t\t\t\t<td align="center">(.*?)'#预约开始时间
patten+='</td>\r\n\t\t\t\t\t\t\t\t\t<td align="center">(.*?)'#预约截至时间
patten+='</td>\r\n\t\t\t\t\t\t\t\t\t<td align="center">(.*?)'#可预约
patten+='</td>\r\n\t\t\t\t\t\t\t\t\t<td align="center">(.*?)'#已预约
patten+='</td>\r\n\t\t\t\t\t\t\t\t\t<td align="center">(.*?)'#学时
m1=re.findall(patten, response.text)
m2=re.findall('<form action="(.*?)" method="post"', response.text)
return True,m1,m2
else:
print("请求失败")
return False,[],[]
except Exception as e:
print(e)
return False,[],[]
# 选课提交
def XuanKe(url):
try:
URL=baseURL+url
params={
"submit_type":"book_submit",
}
# book_cancel
response = requests.post(URL, data=params, headers=req_header,cookies=SetCookies(cookies_str))
if response.status_code==200:
return True
except Exception as e:
print(e)
return False
# 任务包装
def run():
flag,m1,m2=getPostURL(17,2,second_id)#抢第17周,周二的课
if flag:
for i in m1:
print(i)
pass
for i in m2:
flag=XuanKe(i)
if flag:
#print(text)
pass
else:
print("脚本有误!")
# 主函数
def main():
for i in range(100000):
start=time.time()
run()
print("第"+str(i+1)+"次请求,请求时间:"+str(round(time.time()-start,2))+"秒")
#time.sleep(3)#延时0.5s
三、效果与总结
我准备抢的是,17周,周二的考试,13:30开抢,我提前1分钟在跑脚本,结果第一个抢到