机制分析
夸克浏览器的答案获取机制如下图所示:
简单的来说,如果需要正确的获得答案,那么就需要构造请求头。这里的目标网页是动态的,也就是说夸克浏览器加了反爬措施。经研究发现,反爬措施主要有四点:
1)需要设置User-Agent
2)动态cookie
3)访问速度过快,会封ip
4) 请求协议头的构造
基于解决以上四点,可以这样操作:
1)User-Agent可以通过直接抓取夸克浏览器的请求协议头(js中User-Agent不能含有空格,python不需要 考虑)
2)经过多次测试发现,请求几次就会出现404状态,而返回值就包含cookie信息,那么下次访问加载返回的cookie信息,就可以解决动态cookie
3)但对于请求过快的话,延时2多一点就能解决,设置延时1s,没有问题(经过测试500ms的话就会封ip,封过ip后几分钟之后就会解封)
4)经研究发现,请求协议头含有时间戳参数,需要动态构造
代码
基于以上分析,可以写出一下python代码:
import time
import requests
import re
import json
import pprint
class Spider(object):
url = 'https://answer-quark.sm.cn/answer/curr?format=json'
cookie="自己获取"
header = {
'path': '/answer/index?format=json&activity=thyx',
'scheme': 'https',
'accept':'application/json',
'accept-language':'zh-CN,zh;q=0.9',
'referer':'https://answer-quark.sm.cn/answer/? uc_param_str=dnntnwvepffrgibijbprsvdsdicheiniut&source=search',
'User-Agent': '自己抓取'}
def index_request(self):
url = 'https://answer-quark.sm.cn/answer/curr?format=json&_t='+str((int)(time.time()))+'&activity=thyx'
while True:
try:
response=requests.get(url,headers=self.header,cookies=self.cookie)
result = response.text
# print(result)
if 'html' not in result:
res = json.loads(result)
if res['data']['correct'] is not '':
answer = int(res['data']['correct'])+1
if answer!=0:
print(str(answer)+res['data']['options'][int(res['data']['correct'])]['title'])
else:
sec=re.findall('sec=\w+',result)
cookiesec=''.join(sec).replace('sec=','')
print(cookiesec)
self.cookie['sec']=cookiesec
time.sleep(1)
except Exception as e:
pass
if __name__== '__main__':
spider=Spider()
spider.index_request()
总结
虽然本次实践的项目比较简单。但是用来学习已经足够了,其中包含的主要知识点如下:
- App爬虫
- 4点反爬机制
- 请求协议头的构造