MOOC网课爬虫逆向(五)
先尝试把代码写出来
思路:
1.通过原有的线代测验里进行一次开始测验的请求拿到服务器生成的aid
2.然后通过前文提到的他山之石,c程获取到答案
这里的url我就不贴出来了,cookie信息也不给看了,不然我账号有风险
#获取答案请求的data
data = {
"tid":"119006","aid":'2707578304',"withStdAnswerAndAnalyse":55
}
得到问题的aid
def getquestion():
#获取问题,得到aid,并设置下文aid
rep = requests.post(url=url_getquestion,data=data2,headers=headers2)
aid = rep.json()['result']['aid']
rep.close()
data['aid'] = aid
#data3['paperDto']['aid'] = aid
获取答案
def getanswer():
#通过aid获取答案
rep = requests.post(url=url_answer,data=data,headers=headers,proxies=proxy,varify=False)
rep_dic = rep.json()
rep_list = rep_dic['result']['objectiveQList']
question_lst = []
for e in rep_list:
temp = question()
temp.parse(e)
question_lst.append(temp)
rep.close()
return question_lst
这个question是我写的一个类,方便后面的存进html文件中
class question:
def __init__(self):
#题目的id
self.id = 0
#问题题目:文本和图片
self.question = ''
self.question_text = ''
self.question_photo = ''
#问题的选项:文字和图片以及对错还有id
self.option = []
pass
def parse(self,dic):
self.id = dic['id']
self.question = dic['title']
self.option = dic['optionDtos']
pass
#进行到列表的转换,方便后面进行写入
def convert(self):
lst = []
lst.append('<p>'+"-"*100+'</p>')
lst.append('<p>'+str(self.id)+'</p>')
lst.append('<p>'+self.question+'</p>')
for e in self.option:
#lst.append('<p>'+str(e['id'])+'</p>')
lst.append('<p>'+e['content']+'</p>')
if e['answer']:
lst.append('<p>'+'正确!'.center(20,'*')+'</p>')
else:
lst.append('<p>'+''.center(20,'*')+'</p>')
return lst
saveanswer把id存到id3.txt,题目和答案写道list3.html中
这里写的和屎一样,说下思路吧:
记录下每一题的id,当id3.txt中没有这题的id时代表这题没出现过,于是就将id写入,并且将题目和正确答案存入list3.html中
def saveanswer(question_save_lst):
with open('list3.html','a+',encoding='utf-8') as f:
f2 = open('id3.txt','r+',encoding='utf-8')
id_lst = []
for e in f2.readlines():
id_lst.append(int(e))
#先写id
for e in question_save_lst:
if e.id not in id_lst:
id_lst.append(e.id)
lst = e.convert()
f.writelines(lst)
text_lst = []
for e in id_lst:
text_lst.append(str(e)+'\n')
f2.close()
f2 = open('id2.txt','w',encoding='utf-8')
f2.writelines(text_lst)
f2.close()
f.close()
主函数
if __name__ == "__main__":
x = int(input("输入本次运行次数:"))
for i in range(0,x):
print(f"现在开始第{i}次运行".center(50,'-'))
getquestion()
lst = getanswer()
saveanswer(lst)
print("运行结束,请在id.txt下查看得到的题目id和list.html查看题目和答案")
开始跑跑看
错误了,看看参数
简单而言就是两次请求太快了,可以sleep(1)暂停一下
在跑跑
还是有问题,没有获取到数据!但是aid是有的!到底怎么回事呢?
这时候该怎么办找问题呢?
别急,加个代理,burpsuite抓包一下
#加个代理,方便抓包
proxy = {
'http':'127.0.0.1:8080',
'https':'127.0.0.1:8080'
}
def getanswer():
time.sleep(1)
#通过aid获取答案
rep = requests.post(url=url_answer,data=data,headers=headers,proxies=proxy,varify=False)
rep_dic = rep.json()
rep_list = rep_dic['result']['objectiveQList']
question_lst = []
for e in rep_list:
temp = question()
temp.parse(e)
question_lst.append(temp)
rep.close()
return question_ls
在泡一泡,出现这种情况
把varify设置为False把电脑的代理打开
再跑跑
答案和id都有了,感觉已经成功了!
但是发现aid一直不变,这就意味着我们只能去得到一个测验的答案!