背景
浏览器在访问网页时会发送很多http请求(request),服务器返回响应(response),浏览器拿到响应数据后渲染出来,当然我们可以尝试使用python模拟浏览器发送出这些请求来了解交互的细节,甚至可以做一些自动化的工作。
实现
在使用chrome浏览器打开网页时,按ctrl+shift+I可以打开开发者工具页面,这个页面能监控到后台发送的请求,如下图。重点关注request的header,payload这部分。
下面示例下如何用python 发送一个request。
myUrl = 'https://abc/eft'
headers = {
'Connection': 'keep-alive',
'Accept': '*/*',
'Content-Type': 'application/json;charset=UTF-8',
'Content-Length': '156',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN,zh;q=0.9',
'User-Agent': 'SamClub/5.0.45 (iPhone; iOS 15.4; Scale/3.00)',
'device-name': 'iPhone14,3',
'device-os-version': '15.4',
'device-type': 'ios',
'auth-token': authtoken,
'app-version': '5.0.45.1'
}
data = {
"perDateList": date_list,
"storeDeliveryTemplateId": good_store.get('storeDeliveryTemplateId')
}
try:
ret = requests.post(url=myUrl, headers=headers, data=json.dumps(data),timeout = cfg.timeout )
response_data = ret.json()
except Exception as e:
lg.info('getCapacityData [Error]: ' + str(e))
request.post需要的headers数据可以从chrome的request headers字段获取,data为对api调用的参数,即为payload中的json数据。注意这里使用data和json都是可以的。如果是data,那么需要自己手动encode为字节流(可能需要编码成utf-8),如果时json,那么可以直接将字典类型的数据作为参数传入,post函数后台会将其编码为字节流。
request的结果可以通过json成员函数进行反序列化。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)