写这篇文章是出于对猿人学第十题的少见反爬的好奇。
如题:
猿人学练习平台第十题
也可以参考 http://match.yuanrenxue.com/match/3 同样的反爬策略。
- F12调试下发现无加密参数,在postman上调试拿不到对应数据
- 将header所有参数都加入,依然得不到数据
- 下面是对应的接口头部信息:
题目已经给出线索,请求规律检测- headers,从此处出发。将所有的参数按照顺序排列。(不过在此踩了一个坑,开发者工具上的排序并不是原始顺序,而是按字母顺序。后采用抓包工具得到对应的header参数顺序)。
得到正确的顺序后剩下的就是模拟请求,此处踩了两个坑。
- header中 Content-Type = application/x-www-form-urlencoded; charset=UTF-8,这里并不是form-data方式,具体可自行百度
- requests默认情况下,会更改一定好的header参数顺序
方案:
- 使用params传递page参数
- 采用session方式定制header
h = {
'Host': 'www.python-spider.com',
'Connection': 'keep-alive',
'Content-Length': '0',
'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="90", "Google Chrome";v="90"',
'Accept': 'application/json, text/javascript, */*; q=0.01',
'X-Requested-With': 'XMLHttpRequest',
'sec-ch-ua-mobile': '?0',
'User-Agent': '******************',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Origin': 'https://www.python-spider.com',
'Sec-Fetch-Site': 'same-origin',
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Dest': 'empty',
'Referer': 'https://www.python-spider.com/challenge/10',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'zh-CN,zh;q=0.9',
'Cookie': '******'
}
params = {'page': 1}
url = 'https://www.python-spider.com/api/challenge10'
# 先session
session = requests.Session()
# 后session clear,clear这个是比较关键的写法。
session.headers.clear()
session.headers.update(h)
resp = session.post(url, params=params, verify=False)
总结
header参数顺序反爬很少见,确实算是一个较冷门的点。不过,也了解到requests库session的特殊用法。