分享一款中国大学慕课MOOC免费答题软件脚本,亲测好用,解放了我的双手
下载链接:https://pan.baidu.com/s/1DOEWRYvOzo1Dwb7_K3PPSQ#/
下面是答案源码脚本内容分享:欢迎大佬门指正
import sys
if name == ‘main’:
sys.path.append(’…/’)
import re
import time
import random
import string
import requests
import rsa
import base64
import json
from urllib import parse
from pprint import pprint
from datetime import datetime
from Crypto.PublicKey import RSA
from src.Config import *
from src.Parse2Data import *
all = [
‘BrowseCourse’,
]
def encrypt(password):
pubkey = ‘-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5gsH+AA4XWONB5TDcUd+xCz7e\njOFHZKlcZDx+pF1i7Gsvi1vjyJoQhRtRSn950x498VUkx7rUxg1/ScBVfrRxQOZ8\nxFBye3pjAzfb22+RCuYApSVpJ3OO3KsEuKExftz9oFBv3ejxPlYc5yq7YiBO8XlT\nnQN0Sa4R4qhPO3I2MQIDAQAB\n-----END PUBLIC KEY-----’
rsa_key = RSA.importKey(pubkey)
crypt = rsa.encrypt(password.encode(), rsa_key)
ctypt_str = base64.b64encode(crypt).decode()
return ctypt_str
class BrowseCourse():
‘’’
类中类的一个示范
‘’’
class LoginCourse():
‘’’
通过手机号和邮箱登录慕课账号
‘’’
phone_imooc_url = ‘https://reg.icourse163.org/dl/yd/ini?pd=imooc&pkid=cjJVGQM&pkht=www.icourse163.org&channel=1’
email_imooc_url = ‘https://reg.icourse163.org/dl/ini?pd=imooc&pkid=cjJVGQM&pkht=www.icourse163.org&channel=0’
phone_tk_url = ‘https://reg.icourse163.org/dl/yd/gt’
email_tk_url = ‘https://reg.icourse163.org/dl/gt’
phone_sess_url = ‘https://reg.icourse163.org/dl/yd/lpwd’
email_sess_url = ‘https://reg.icourse163.org/dl/l’
phone_cookie_url = ‘https://www.icourse163.org/passport/logingate/changeCookie.htm?type=ursCellphone’
email_cookie_url = ‘https://www.icourse163.org/passport/logingate/changeCookie.htm?type=urs’
def __init__(self, username, password, parent=None):
self.init()
self.parent = parent if parent else BrowseCourse.Parent()
self.username = username
self.password = encrypt(password)
def init(self):
self.headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36',
'cookie': 'JSESSIONID-WYTXZDL=rDrJqTRndbJHlxQFUo%2F3yHZpRq5Nj1ycAPPDnajKPn0%2BDm8iVnbzIS%2BZz9Zvn63tXf8dTTQfPfONqgQeaMdWKFjvuZYFI81nSNGMKhhxUr2SLtywJZXBYRiqF3vHGP9Wx%2BjfJKctSnZeH3ykd0hSZt%2BRNr6umB%2BhJkjlphSlgKgB90w6%3A1567604303120',
}
self.tk_params = {
'un': None, #username,
'pd': 'imooc',
'pkid': 'cjJVGQM',
}
self.sess_data = {
"un": None, #username,
"pw": None, #encrypt(password),
"pd": "imooc",
"pkid": "cjJVGQM",
"tk": None, #tk,
}
def set_phone_imooc(self):
try:
res = request_get(self.phone_imooc_url, headers=self.headers)
cookie_dict = dict(res.cookies)
imooc_value = cookie_dict.get('l_yd_s_imooccjJVGQM')
if imooc_value:
self.headers['cookie'] += ';l_yd_s_imooccjJVGQM='+imooc_value
except RequestError:
pass
def set_email_imooc(self):
try:
res = request_get(self.email_imooc_url, headers=self.headers)
cookie_dict = dict(res.cookies)
imooc_value = cookie_dict.get('l_s_imooccjJVGQM')
if imooc_value:
self.headers['cookie'] += ';l_s_imooccjJVGQM='+imooc_value
except RequestError:
pass
def init_login(self):
self.headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36',
'cookie': 'JSESSIONID-WYTXZDL=rDrJqTRndbJHlxQFUo%2F3yHZpRq5Nj1ycAPPDnajKPn0%2BDm8iVnbzIS%2BZz9Zvn63tXf8dTTQfPfONqgQeaMdWKFjvuZYFI81nSNGMKhhxUr2SLtywJZXBYRiqF3vHGP9Wx%2BjfJKctSnZeH3ykd0hSZt%2BRNr6umB%2BhJkjlphSlgKgB90w6%3A1567604303120',
}
self.headers['user-agent'] += '--'+ ''.join(random.sample(string.ascii_letters+string.digits, 32))
self.set_phone_imooc()
self.set_email_imooc()
def get_tk(self, tk_url):
try:
self.tk_params['un'] = self.username
res = request_get(tk_url, params=self.tk_params, headers=self.headers).json()
# print(res)
if self.parent.stop:
return None
return res.get('tk')
except RequestError:
return None
def get_sess(self, sess_url, tk):
try:
self.sess_data['un'] = self.username
self.sess_data['pw'] = self.password
self.sess_data['tk'] = tk
res = request_post(sess_url, json=self.sess_data, headers=self.headers)
# print(res.text)
if self.parent.stop:
return None
cookies_dict = requests.utils.dict_from_cookiejar(res.cookies)
# print(cookies_dict)
if sess_url==self.phone_sess_url:
if cookies_dict.get('NTES_YD_SESS'):
cookie = 'NTES_YD_SESS='+cookies_dict.get('NTES_YD_SESS')
return cookie
elif sess_url==self.email_sess_url:
if cookies_dict.get('NTES_SESS'):
cookie = 'NTES_SESS='+cookies_dict.get('NTES_SESS')
return cookie
return None
except RequestError:
return None
def get_cookie(self, cookie_url, sess):
try:
headers = self.headers.copy()
headers['cookie'] = sess
res = request_get(cookie_url, headers=headers)
if self.parent.stop:
return None
cookies_dict = requests.utils.dict_from_cookiejar(res.cookies)
# print(cookies_dict)
if cookies_dict.get('STUDY_SESS'):
cookie = 'STUDY_SESS='+cookies_dict.get('STUDY_SESS')
return cookie
return None
except RequestError:
return None
def login_by_phone(self):
tk = self.get_tk(self.phone_tk_url)
if not self.parent.stop and tk:
sess = self.get_sess(self.phone_sess_url, tk)
if not self.parent.stop and sess:
cookie = self.get_cookie(self.phone_cookie_url, sess)
if not self.parent.stop and cookie:
Config_Cookies.setCookie(self.username, cookie)
return True
return False
def login_by_email(self):
tk = self.get_tk(self.email_tk_url)
if not self.parent.stop and tk:
sess = self.get_sess(self.email_sess_url, tk)
if not self.parent.stop and sess:
cookie = self.get_cookie(self.email_cookie_url, sess)
if not self.parent.stop and cookie:
Config_Cookies.setCookie(self.username, cookie)
return True
return False
def login(self):
isLogin = False
self.init_login()
try:
isLogin = self.login_by_phone()
if not self.parent.stop and not isLogin:
isLogin = self.login_by_email()
except RequestError:
pass
return isLogin
class Parent():
stop = False
base_url = 'https://www.icourse163.org/'
course_url = 'https://www.icourse163.org/course/'
spoc_url = 'https://www.icourse163.org/spoc/course/'
info_url = 'https://www.icourse163.org/dwr/call/plaincall/CourseBean.getLastLearnedMocTermDto.dwr'
browse_url = 'https://www.icourse163.org/web/j/courseBean.saveMocContentLearn.rpc?csrfKey=2bcefbdcde2740f09e7462ece1e8ac3f'
uid_url = 'https://www.icourse163.org/web/j/mocCourseV2RpcBean.getMemberLearningRate.rpc?csrfKey=2bcefbdcde2740f09e7462ece1e8ac3f'
submit_url = 'https://www.icourse163.org/dwr/call/plaincall/MocQuizBean.submitAnswers.dwr'
paper_url = 'https://www.icourse163.org/dwr/call/plaincall/MocQuizBean.getQuizPaperDto.dwr'
homepaper_url = 'https://www.icourse163.org/dwr/call/plaincall/MocQuizBean.getHomeworkPaperDto.dwr'
quiz_url = 'https://www.icourse163.org/dwr/call/plaincall/MocQuizBean.getQuizInfo.dwr'
homework_url = 'https://www.icourse163.org/dwr/call/plaincall/MocQuizBean.getHomeworkInfo.dwr'
joined_url = 'https://www.icourse163.org/web/j/learnerCourseRpcBean.getMyLearnedCoursePanelList.rpc?csrfKey=2bcefbdcde2740f09e7462ece1e8ac3f'
login_url = 'https://www.icourse163.org/passport/reg/icourseLogin.do'
member_url = 'https://www.icourse163.org/web/j/mocCourseV2RpcBean.getMemberLearningRate.rpc?csrfKey=2bcefbdcde2740f09e7462ece1e8ac3f'
userpost_url = 'https://www.icourse163.org/dwr/call/plaincall/PostBean.getUserFollowedPosts.dwr'
getform_url = 'https://www.icourse163.org/dwr/call/plaincall/MocForumBean.getForumListByTermId.dwr'
getpost_url = 'https://www.icourse163.org/dwr/call/plaincall/PostBean.getAllPostsPagination.dwr'
getreply_url = 'https://www.icourse163.org/dwr/call/plaincall/PostBean.getPaginationReplys.dwr'
addreply_url = 'https://www.icourse163.org/dwr/call/plaincall/MocForumBean.addReply.dwr'
def __init__(self, mooc_username, brush_work=False, parent=None):
self.init()
self.parent = parent if parent else BrowseCourse.Parent()
self.mooc_username = mooc_username
self.headers['cookie'] += Config_Cookies.getCookie(mooc_username)
# self.headers['cookie'] += 'STUDY_SESS="qiKx0Y0eh91E9ZBcXYx2TjNb8fFnm9q+0mHIWmOgDjTFQaqlWtruZ6ITugCK1sqIw+OatGiPnWRBTvR57q/HuuyiUW/8cqcxTD7HjrTU/rJ6YQKPs9wmBX2MXS2EanJBTuwBhvd8wvbMMYTusXnhMyNcRuc2GgZRE/NJIup76nUraIhXip7cxuujNaDWvdb5"'
self.baseInfos = {}
self.brush_work = brush_work
def init(self):
self.info_data = {
'callCount': '1',
'scriptSessionId': '${scriptSessionId}190',
'httpSessionId': '2a3aadd7599046fc95756c6272e620b1',
'c0-scriptName': 'CourseBean',
'c0-methodName': 'getLastLearnedMocTermDto',
'c0-id': '0',
'c0-param0': None, # 'number:tid',
'batchId': str(int(time.time()*1000)),
}
self.video_data = {
"index": 1,
"finished": True,
"unitId": None, # 1214951981,
"courseId": None, # 20012,
"lessonId": None, # 1211919789,
"videoId": None, # 731007,
"termId": None, # 1206946235,
"userId": None, # "1396346603",
"contentType": 1,
# 'callCount': '1',
# 'scriptSessionId': '${scriptSessionId}190',
# 'httpSessionId': '2a3aadd7599046fc95756c6272e620b1',
# 'c0-scriptName': 'CourseBean',
# 'c0-methodName': 'saveMocContentLearn',
# 'c0-id': '0',
# 'c0-e1': None, # 'number:id',
# 'c0-e2': 'number:0',
# 'c0-e3': 'boolean:false',
# 'c0-e4': 'number:1',
# 'c0-e5': 'number:20000',
# 'c0-e6': None, # 'number:courseId',
# 'c0-e7': None, # 'number:lessonId',
# 'c0-e8': None, # 'number:contentId',
# 'c0-e9': None, # 'number:tid,
# 'c0-e10': 'null:null',
# 'c0-e11': None, # 'string:uid',
# 'c0-e12': 'number:1',
# 'c0-param0': 'Object_Object:{unitId:reference:c0-e1,videoTime:reference:c0-e2,finished:reference:c0-e3,index:reference:c0-e4,duration:reference:c0-e5,courseId:reference:c0-e6,lessonId:reference:c0-e7,videoId:reference:c0-e8,termId:reference:c0-e9,resolutionType:reference:c0-e10,userId:reference:c0-e11,contentType:reference:c0-e12}',
# 'batchId': str(int(time.time()*1000)),
}
self.subject_data = {
"unitId": None, # 1214951984,
"finished": True,
"contentType": None,
# 'callCount': '1',
# 'scriptSessionId': '${scriptSessionId}190',
# 'httpSessionId': '670f6d6c44e3429485ef3c423603f1ae',
# 'c0-scriptName': 'CourseBean',
# 'c0-methodName': 'saveMocContentLearn',
# 'c0-id': '0',
# 'c0-e1': None, # 'number:id',
# 'c0-e2': 'boolean:true',
# 'c0-e3': None, # 'number:contentId', 4/5/6
# 'c0-param0': 'Object_Object:{unitId:reference:c0-e1,finished:reference:c0-e2,contentType:reference:c0-e3}',
# 'batchId': str(int(time.time()*1000)),
}
self.document_data = {
"unitId": None, # 1214951990,
"pageNum": 1,
"finished": True,
"contentType": 3,
# 'callCount': '1',
# 'scriptSessionId': '${scriptSessionId}190',
# 'httpSessionId': '670f6d6c44e3429485ef3c423603f1ae',
# 'c0-scriptName': 'CourseBean',
# 'c0-methodName': 'saveMocContentLearn',
# 'c0-id': '0',
# 'c0-e1': None, # 'number:id',
# 'c0-e2': 'number:1',
# 'c0-e3': 'boolean:false',
# 'c0-e4': 'number:3',
# 'c0-param0': 'Object_Object:{unitId:reference:c0-e1,pageNum:reference:c0-e2,finished:reference:c0-e3,contentType:reference:c0-e4}',
# 'batchId': str(int(time.time()*1000)),
}
self.paper_data = {
'callCount': '1',
'scriptSessionId': '${scriptSessionId}190',
'httpSessionId': 'd39c1bc9705649b48d0a1e6bbb4dc516',
'c0-scriptName': 'MocQuizBean',
'c0-methodName': 'getQuizPaperDto', # 'getQuizInfo' 'getHomeworkPaperDto' 'getHomeworkInfo'
'c0-id': '0',
'c0-param0': None, # 'string:pid',
'c0-param1': 'number:-1',
'c0-param2': 'boolean:false',
'batchId': str(int(time.time()*1000)),
}
self.joined_data = {
'type': '30',
'p': None, # '1'
'psize': '100',
'courseType': None, # '1' '2'
}
self.login_data = {
'username': None,
'passwd': None,
}
self.member_data = {
'termId': None, # '1206950202',
}
self.userpost_data = {
'callCount': '1',
'scriptSessionId': '${scriptSessionId}190',
'httpSessionId': '05de788ab6e74b8399f2150cf6d58ea0',
'c0-scriptName': 'PostBean',
'c0-methodName': 'getUserFollowedPosts',
'c0-id': '0',
'c0-param0': None, # 'number:1206950202',
'c0-param1': None, # 'string:1397621151',
'c0-param2': 'number:1',
'c0-param3': 'number:20',
'batchId': str(int(time.time()*1000)),
}
self.getform_data = {
'callCount': '1',
'scriptSessionId': '${scriptSessionId}190',
'httpSessionId': '05de788ab6e74b8399f2150cf6d58ea0',
'c0-scriptName': 'MocForumBean',
'c0-methodName': 'getForumListByTermId',
'c0-id': '0',
'c0-param0': None, # 'number:1206950202',
'c0-param1': 'boolean:false',
'c0-param2': 'boolean:true',
'batchId': str(int(time.time()*1000)),
}
self.getpost_data = {
'callCount': '1',
'scriptSessionId': '${scriptSessionId}190',
'httpSessionId': '05de788ab6e74b8399f2150cf6d58ea0',
'c0-scriptName': 'PostBean',
'c0-methodName': 'getAllPostsPagination',
'c0-id': '0',
'c0-param0': None, # 'number:1206950202',
'c0-param1': None, # 'string:1209634863',
'c0-param2': 'number:3',
'c0-param3': 'string:1',
'c0-param4': 'number:20',
'c0-param5': 'boolean:false',
'c0-param6': 'null:null',
'batchId': str(int(time.time()*1000)),
}
self.getreply_data = {
'callCount': '1',
'scriptSessionId': '${scriptSessionId}190',
'httpSessionId': '05de788ab6e74b8399f2150cf6d58ea0',
'c0-scriptName': 'PostBean',
'c0-methodName': 'getPaginationReplys',
'c0-id': '0',
'c0-param0': None, # 'number:1213305997',
'c0-param1': 'number:2',
'c0-param2': 'number:1',
'batchId': str(int(time.time()*1000)),
}
self.addreply_data = {
'callCount': '1',
'scriptSessionId': '${scriptSessionId}190',
'httpSessionId': '05de788ab6e74b8399f2150cf6d58ea0',
'c0-scriptName': 'MocForumBean',
'c0-methodName': 'addReply',
'c0-id': '0',
'c0-e1': None, # 'number:1213305997',
'c0-e2': None, # 'string:%3Cp%3E%E5%BD%93%E5%88%AB%E4%BA%BA%E5%AF%B9%E8%87%AA%E5%B7%B1%E6%9C%89%E5%A8%81%E8%83%81%E6%97%B6%E5%80%99%E5%92%AF%3C%2Fp%3E',
'c0-e3': 'number:0',
'c0-param0': 'Object_Object:{postId:reference:c0-e1,content:reference:c0-e2,anonymous:reference:c0-e3}',
'c0-param1': 'Array:[]',
'batchId': str(int(time.time()*1000)),
}
self.headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36',
'cookie': 'NTESSTUDYSI=2bcefbdcde2740f09e7462ece1e8ac3f;',
}
self.zombie_headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36',
'cookie': 'NTESSTUDYSI=2bcefbdcde2740f09e7462ece1e8ac3f;',
}
def autoBrowse(self, ctid):
for _ in range(5):
try:
browse_state = (self._get_ctid(ctid) and self._get_info() and self.browse())
exam_state = self.get_exam_state()
return (browse_state, exam_state)
except RequestError:
continue
return (False, None)
def isLogin(self):
try:
return self._isLogin()
except RequestError:
pass
return False
def login(self, mooc_password):
try:
self.login_data['username'] = self.mooc_username
self.login_data['passwd'] = mooc_password
res = request_post(self.login_url, data=self.login_data, headers=self.headers)
cookies_dict = requests.utils.dict_from_cookiejar(res.cookies)
if cookies_dict.get('STUDY_SESS'):
cookie = 'STUDY_SESS='+cookies_dict.get('STUDY_SESS')
Config_Cookies.setCookie(self.mooc_username, cookie)
# print(cookie)
return True
return (not self.parent.stop and BrowseCourse.LoginCourse(self.mooc_username, mooc_password).login())
except RequestError:
return False
def get_joinedCourses(self):
course_list = []
try:
self.joined_data['courseType'] = '2'
spoc_list = self._get_joinedCourses()
course_list += spoc_list
self.joined_data['courseType'] = '1'
mooc_list = self._get_joinedCourses()
course_list += mooc_list
except RequestError:
pass
return course_list
def browse(self):
if not self.baseInfos.get('info') and not self.baseInfos.get('pids'):
return
for _ in range(8):
browse_succeed = (self._browse_video() and self._browse_subject() and self._browse_document())
if not (browse_succeed and self._get_info()):
return False
video_params = self.baseInfos.get('info', {}).get('video_params', [])
subject_params = self.baseInfos.get('info', {}).get('subject_params', [])
document_params = self.baseInfos.get('info', {}).get('document_params', [])
if len(video_params)==0 and len(subject_params)==0:
break
return (self._discuss() and self._answer_papers())
def get_exam_state(self):
exam_state = '----'
if self.baseInfos.get('tid'):
try:
self.info_data['c0-param0'] = 'number:'+self.baseInfos.get('tid')
text = request_post(self.info_url, data=self.info_data, headers=self.headers).text.encode('utf8').decode('unicode_escape')
exam_params_list = re.findall(r'bonusScore.*?deadline=(\d+);.*?examId=\d+;.*?releaseTime=(\d+);.*?trytime=(\d+);.*?type=2;.*?usedTryCount=(\d+);', text)
if len(exam_params_list) >= 1:
exam_params = exam_params_list[-1]
if int(exam_params[3])==0:
if time.time() int(exam_params[0])/1000:
exam_state = '已过期'
else:
exam_state = '未考'
else:
exam_state = '已考'
except RequestError:
pass
return exam_state
def _isLogin(self, _headers=None):
try:
self.info_data['c0-param0'] = 'number:317001'
text = request_post(self.info_url, data=self.info_data, headers=_headers if _headers else self.headers).text.encode('utf8').decode('unicode_escape')
match_courseId = re.search(r'courseId=(\d+);', text)
return bool(match_courseId)
except RequestError:
return False
def _get_joinedCourses(self):
course_list = []
self.joined_data['p'] = '1'
json_dict = request_post(self.joined_url, data=self.joined_data, headers=self.headers).json()
results = json_dict.get('result').get('result')
if results:
mooc_user = Config_User.get_user(self.mooc_username, platform='mooc')
mooc_password = mooc_user.split()[1] if len(mooc_user.split())==2 else ''
course_list += [{'mooc_platform': '中国大学', 'visiable': True,
'brush_state': '未刷', 'exam_state': '----',
'mooc_username': self.mooc_username, 'mooc_password': mooc_password,
'mooc_name':course.get('name'), 'course_id':str(course.get('id')),
'term_id':str(course.get('termPanel').get('id')),
'start_date': str(datetime.fromtimestamp(course.get('termPanel').get('startTime')/1000))[:10],
'close_date': str(datetime.fromtimestamp(course.get('termPanel').get('endTime')/1000))[:10],
'is_spoc':True if self.joined_data.get('courseType')=='2' else False}
for course in results]
pages = json_dict.get('result').get('pagination').get('totlePageCount')
for page in range(2, pages+1):
self.joined_data['p'] = str(page)
results = request_post(self.joined_url, data=self.joined_data, headers=self.headers).json().get('result').get('result')
course_list += [{'mooc_platform': '中国大学', 'visiable': True,
'brush_state': '未刷', 'exam_state': '----',
'mooc_username': self.mooc_username, 'mooc_password': mooc_password,
'mooc_name':course.get('name'), 'course_id':str(course.get('id')),
'term_id':str(course.get('termPanel').get('id')),
'start_date': str(datetime.fromtimestamp(course.get('termPanel').get('startTime')/1000))[:10],
'close_date': str(datetime.fromtimestamp(course.get('termPanel').get('endTime')/1000))[:10],
'is_spoc':True if self.joined_data.get('courseType')=='2' else False}
for course in results]
return course_list
def _get_ctid(self, ctid):
cid, tid = ctid
self.baseInfos['cid'] = cid
self.baseInfos['tid'] = tid
return not self.parent.stop
def _get_true_tid(self):
if self.baseInfos.get('cid') is None or self.baseInfos.get('tid') is None:
return
url = self.spoc_url+'PyJun-'+self.baseInfos.get('cid')+'?tid='+self.baseInfos.get('tid')
text = request_get(url).text
termId_match = re.search(r'currentTermId\s*:\s*"(\d+)"', text)
if termId_match:
true_tid = termId_match.group(1)
return true_tid
return None
def _get_info(self):
if self.baseInfos.get('tid') is None:
return
tid = old_tid = self.baseInfos.get('tid')
self.baseInfos['info'] = {'video_params':[], 'subject_params':[], 'document_params':[]}
self.baseInfos['pids'] = {'test_pids':[], 'work_pids':[]}
for cnt in range(2):
if cnt==1:
tid = self._get_true_tid()
if not tid:
break
self.info_data['c0-param0'] = 'number:'+ tid
courseId = None
while not courseId:
text = request_post(self.info_url, data=self.info_data, headers=self.headers).text.encode('utf8').decode('unicode_escape')
# print(text, type(text), bool(text), len(text))
# with open('text.txt', 'w', encoding='utf8') as f:
# f.write(text)
courseId_match = re.search(r'courseId=(\d+);', text)
if courseId_match:
courseId = courseId_match.group(1)
video_params = re.findall(r'contentId=(\d+);.*?contentType=1;.*?id=(\d+);.*?lessonId=(\d+);.*?viewStatus=0;', text)
subject_params = re.findall(r'contentType=([456]);.*?id=(\d+).*?viewStatus=0;', text)
document_params = re.findall(r'contentType=3;.*?id=(\d+).*?viewStatus=0;', text)
testpid_params = re.findall(r'bonusScore.*?deadline=(\d+);.*?id=(\d+);.*?trytime=(\d+);.*?type=2;.*?usedTryCount=(\d+);', text)
workpid_params = re.findall(r'bonusScore.*?deadline=(\d+);.*?id=(\d+);.*?trytime=(null);.*?type=3;.*?usedTryCount=(\d+);', text)
if video_params or subject_params or document_params or testpid_params or workpid_params:
if cnt==1:
self.baseInfos['tid'] = tid
self.baseInfos['info']['video_params'] += [{'unitId':params[1], 'courseId':courseId,
'lessonId':params[2], 'videoId':params[0],
'termId':tid}
for params in video_params]
self.baseInfos['info']['subject_params'] += [{'unitId':params[1], 'contentType':params[0]}
for params in subject_params]
self.baseInfos['info']['document_params'] += [{'unitId':param} for param in document_params]
self.baseInfos['pids']['test_pids'] += [pids[1] for pids in testpid_params if int(pids[0])/1000>time.time() and int(pids[2])>int(pids[3])]
self.baseInfos['pids']['work_pids'] += [pids[1] for pids in workpid_params if int(pids[0])/1000>time.time() and int(pids[3])==0]
# self.baseInfos['pids']['work_pids'] = [pids[1] for pids in workpid_params if int(pids[0])/1000>time.time()]
# print(self.baseInfos)
self.baseInfos['tid'] = old_tid
return not self.parent.stop
def _browse_video(self):
for video_data in self.baseInfos.get('info').get('video_params', []):
self.video_data.update(video_data)
request_post(self.browse_url, data={'dto':json.dumps(self.video_data)}, headers=self.headers)
if self.parent.stop:
return False
return True
def _browse_subject(self):
for subject_data in self.baseInfos.get('info').get('subject_params', []):
self.subject_data.update(subject_data)
request_post(self.browse_url, data={'dto':json.dumps(self.subject_data)}, headers=self.headers)
if self.parent.stop:
return False
return True
def _browse_document(self):
for document_data in self.baseInfos.get('info').get('document_params', []):
self.document_data.update(document_data)
request_post(self.browse_url, data={'dto':json.dumps(self.document_data)}, headers=self.headers)
if self.parent.stop:
return False
return True
def _get_scores(self):
if self.baseInfos.get('tid') is None:
return
self.info_data['c0-param0'] = 'number:'+self.baseInfos.get('tid')
text = request_post(self.info_url, data=self.info_data, headers=self.headers).text.encode('utf8').decode('unicode_escape')
scores = re.findall(r'bonusScore.*?totalScore=(.*?);.*?type=2;.*?userScore=(.*?);', text)
return scores
def _get_exist_aid(self, pid, _headers=None, isHome=False):
data = self.paper_data.copy()
data['c0-methodName'] = 'getHomeworkInfo' if isHome else 'getQuizInfo'
data['c0-param0'] = 'number:'+pid
data['c0-param1'] = 'null:null'
text = request_post(self.homework_url if isHome else self.quiz_url, data=data, headers=_headers if _headers else self.headers).text.encode('utf8').decode('unicode_escape')
if isHome:
exist_aid_list = list(set(re.findall(r'aid:(\d+),', text)))
if not exist_aid_list and _headers:
aid = self._get_aid(pid, _headers=_headers, isHome=True)
if aid:
answer_text = self._extract_answer(pid, aid, _headers=_headers, isHome=True)
self._submit_answer(aid, answer_text, _headers=_headers)
text = request_post(self.homework_url if isHome else self.quiz_url, data=data, headers=_headers).text.encode('utf8').decode('unicode_escape')
exist_aid_list = list(set(re.findall(r'aid:(\d+),', text)))
else:
exist_aid_list = list(set(re.findall(r'\.aid=(\d+);', text)))[:5] # 取前 5 次提交记录就够了
if _headers:
match_count = re.search(r'totalTryCount:(\d+)', text)
if match_count:
total_count = min(int(match_count.group(1)), 5) # 至多提交 5 次
used_count = len(exist_aid_list)
if total_count > used_count:
for _ in range(used_count, total_count):
aid = self._get_aid(pid, _headers=_headers)
if aid:
answer_text = self._extract_answer(pid, aid, _headers=_headers)
self._submit_answer(aid, answer_text, _headers=_headers)
text = request_post(self.homework_url if isHome else self.quiz_url, data=data, headers=_headers).text.encode('utf8').decode('unicode_escape')
exist_aid_list = list(set(re.findall(r'\.aid=(\d+);', text)))
return exist_aid_list
def _get_aid(self, pid, _headers=None, isHome=False):
data = self.paper_data.copy()
data['c0-param0'] = 'string:'+pid
if isHome:
data['c0-param1'] = 'null:null'
data['c0-methodName'] = 'getHomeworkPaperDto'
data['c0-param3'] = 'number:1'
data['c0-param4'] = 'null:null'
text = request_post(self.homepaper_url if isHome else self.paper_url, data=data, headers=_headers if _headers else self.headers).text.encode('utf8').decode('unicode_escape')
match_aid = re.search(r'aid:(\d+),', text)
aid = match_aid.group(1) if match_aid else None
return aid
def _extract_answer(self, pid, aid, _headers=None, isHome=False):
data = self.paper_data.copy()
data['c0-param0'] = 'string:'+pid
data['c0-param1'] = 'number:'+aid
data['c0-param2'] = 'boolean:true'
answer_text = request_post(self.homepaper_url if isHome else self.paper_url, data=data, headers=_headers if _headers else self.headers).text.encode('utf8').decode('unicode_escape')
# print(text)
return answer_text
def _login_zombie(self, zombie_username, zombie_password):
logined = False
zombie_headers = self.zombie_headers.copy()
login_data = self.login_data.copy()
origin_cookie = zombie_headers.get('cookie')
cookie = Config_Cookies.getCookie(zombie_username, platform='zombie')
if cookie:
zombie_headers['cookie'] = origin_cookie+cookie
logined = self._isLogin(_headers=zombie_headers)
if not logined:
zombie_headers['cookie'] = origin_cookie
login_data['username'] = zombie_username
login_data['passwd'] = zombie_password
res = request_post(self.login_url, data=login_data, headers=zombie_headers)
cookies_dict = requests.utils.dict_from_cookiejar(res.cookies)
if cookies_dict.get('STUDY_SESS'):
cookie = 'STUDY_SESS='+cookies_dict.get('STUDY_SESS')
Config_Cookies.setCookie(zombie_username, cookie, platform='zombie')
logined = True
else:
Config_Cookies.setCookie(zombie_username, '', platform='zombie')
return logined
def _get_answer(self, pid, isHome=False):
# total_answer_dict = {}
total_answer_dict = Config_User.get_answers(self.baseInfos.get('tid'), pid, 'mooc')
if not total_answer_dict:
total_answer_text = ''
zombie_headers = self.zombie_headers.copy()
origin_cookie = zombie_headers.get('cookie')
for zombie_username, zombie_password in Config_User.zombie_accounts:
if not self._login_zombie(zombie_username, zombie_password):
continue
cookie = Config_Cookies.getCookie(zombie_username, platform='zombie')
zombie_headers['cookie'] = origin_cookie+cookie
exist_aid_list = self._get_exist_aid(pid, _headers=zombie_headers, isHome=isHome)
for exist_aid in exist_aid_list:
answer_text = self._extract_answer(pid, exist_aid, _headers=zombie_headers, isHome=isHome)
total_answer_text += answer_text
if isHome:
break
total_answer_dict = Parse2Data.parse2dict(total_answer_text)
Config_User.set_answers(self.baseInfos.get('tid'), pid, 'mooc', total_answer_dict)
# with open('total_answer_dict.txt', 'w', encoding='utf8') as f:
# pprint(total_answer_dict, stream=f)
# print('set_answers!')
# with open('text.txt', 'w', encoding='utf8') as f:
# f.write(total_answer_text)
# else:
# print('has_answers!')
return total_answer_dict
def _get_answer_data(self, answer_text, total_answer_dict=None, aid=None):
answer_dict = Parse2Data.parse2dict(answer_text)
answer_data = Parse2Data.parse2data(answer_dict, total_answer_dict=total_answer_dict, aid=aid)
return answer_data
def _submit_answer(self, aid, answer_text, total_answer_dict=None, _headers=None):
answer_data = self._get_answer_data(answer_text, total_answer_dict=total_answer_dict, aid=aid)
res = request_post(self.submit_url, data=answer_data, headers=_headers if _headers else self.headers)
return res.status_code==200
def _acquire_scores(self, aid):
data = self.paper_data.copy()
data['c0-methodName'] = 'getQuizInfo'
data['c0-param1'] = 'number:'+aid
res_text = request_post(self.quiz_url, data=data, headers=self.headers).text.encode('utf8').decode('unicode_escape')
scores = re.search(r'finalScore=(.*?);.*?totalScore=(.*?);', res_text).groups()[::-1]
return scores
def _answer(self, pid, isHome=False):
aid = self._get_aid(pid, isHome=isHome)
if aid:
answer_text = self._extract_answer(pid, aid, isHome=isHome)
if isHome:
self._submit_answer(aid, answer_text)
answer_text = self._extract_answer(pid, aid, isHome=isHome)
total_answer_dict = self._get_answer(pid, isHome=isHome)
self._submit_answer(aid, answer_text, total_answer_dict=total_answer_dict)
# scores = self._acquire_scores(aid)
# print(pid, scores)
return not self.parent.stop
def _answer_papers(self):
for pid in self.baseInfos.get('pids', {}).get('test_pids', []):
if not self._answer(pid):
return False
# 对作业的自动答题
if self.brush_work:
for pid in self.baseInfos.get('pids', {}).get('work_pids', []):
if not self._answer(pid, isHome=True):
return False
# scores_list = self._get_scores()
# print(scores_list)
return True
def _get_memberId(self):
if self.baseInfos.get('tid') is None:
return
self.member_data['termId'] = self.baseInfos.get('tid')
text = request_post(self.member_url, data=self.member_data, headers=self.headers).text
match = re.search(r'"memberId"\s*:\s*(\d+)', text)
if match:
memberId = match.group(1)
self.baseInfos['mid'] = memberId
def _get_userpost_cnt(self):
if self.baseInfos.get('tid') is None or self.baseInfos.get('mid') is None:
return None
self.userpost_data['c0-param0'] = 'number:'+self.baseInfos.get('tid')
self.userpost_data['c0-param1'] = 'string:'+self.baseInfos.get('mid')
text = request_post(self.userpost_url, data=self.userpost_data, headers=self.headers).text.encode('utf8').decode('unicode_escape')
match = re.search(r'totleCount=(\d+);', text)
if match:
return int(match.group(1))
return None
def _get_form_id(self):
if self.baseInfos.get('tid') is None:
return None
self.getform_data['c0-param0'] = 'number:'+self.baseInfos.get('tid')
text = request_post(self.getform_url, data=self.getform_data, headers=self.headers).text.encode('utf8').decode('unicode_escape')
match = re.search(r'id=(\d+);.*?name="课堂交流区";', text)
if match:
return match.group(1)
return None
def _get_contentId_list(self):
if self.baseInfos.get('tid') is None:
return None
form_id = self._get_form_id()
if not form_id:
return None
self.getpost_data['c0-param0'] = 'number:'+self.baseInfos.get('tid')
self.getpost_data['c0-param1'] = 'string:'+form_id
text = request_post(self.getpost_url, data=self.getpost_data, headers=self.headers).text.encode('utf8').decode('unicode_escape')
contentId_list = re.findall(r'contentId=(\d+);', text)
return contentId_list
def _get_reply_content(self, pid):
self.getreply_data['c0-param0'] = 'number:'+pid
text = request_post(self.getreply_url, data=self.getreply_data, headers=self.headers).text.encode('utf8').decode('unicode_escape')
reply_content_list = re.findall(r'content="(.*?)";', text)
if reply_content_list:
return random.choice(reply_content_list)
return None
def _submit_reply(self, pid, content):
self.addreply_data['c0-e1'] = 'number:'+pid
self.addreply_data['c0-e2'] = 'string:'+parse.quote(content)
request_post(self.addreply_url, data=self.addreply_data, headers=self.headers)
def _discuss(self):
self._get_memberId()
if self.parent.stop:
return
userpost_cnt = self._get_userpost_cnt()
# print(userpost_cnt)
if not self.parent.stop and userpost_cnt is not None:
form_id = self._get_form_id()
# print(form_id)
if not self.parent.stop and form_id:
contentId_list = self._get_contentId_list()
if not self.parent.stop and contentId_list:
pid_list = contentId_list[:10]
# print(pid_list)
for _ in range(userpost_cnt, 5):
if self.parent.stop:
return
pid = random.choice(pid_list)
reply_content = self._get_reply_content(pid)
if not self.parent.stop and reply_content:
self._submit_reply(pid, reply_content)
return not self.parent.stop
def test0():
ctid = (‘1449750162’, ‘1450181445’)
browser_mooc = BrowseCourse(‘15172479942’)
print(browser_mooc._get_ctid(ctid))
print(browser_mooc._get_info())
print(browser_mooc.baseInfos)
def test1():
course_list = BrowseCourse(‘18702728454’).get_joinedCourses()
print(course_list)
print(len(course_list))
def test2():
print(BrowseCourse(“1942844913@qq.com”).isLogin())
def test3():
ctid = (‘1449750162’, ‘1450181445’)
print(BrowseCourse(“15172479942”, brush_work=True).autoBrowse(ctid))
def test4():
print(BrowseCourse(“382296435@qq.com”).login(‘yyx382296435’))
def test5():
pid = ‘1220721424’
# aid = ‘1473086884’
browser_mooc = BrowseCourse(‘17603262125’) # 17680141175 qwerasdf123
aid = browser_mooc._get_aid(pid, isHome=True)
print(aid)
answer_text = browser_mooc._extract_answer(pid, aid, isHome=True)
with open(‘text.txt’, ‘w’, encoding=‘utf8’) as f:
f.write(answer_text)
# print(answer_text)
# answer_data = Parse2Data.parse(answer_text, aid)
# print(answer_data)
# print(browser_mooc._submit_answer(aid, answer_text))
# browser_mooc._get_answer(pid)
# browser_mooc._answer(pid)
def test6():
pid = ‘1219843516’
browser_mooc = BrowseCourse(‘17603262125’)
browser_mooc._answer(pid, isHome=True)
def test7():
ctid = (‘1205806833’, ‘1206624259’)
browser_mooc = BrowseCourse(“icourse@payspun.com”)
browser_mooc._get_ctid(ctid)
print(browser_mooc._discuss())
def test8():
print(BrowseCourse(‘17767513249’).LoginCourse(‘17767513249’, ‘ak2016913’).login())
if name == ‘main’:
# test0()