记录三种添加cookie保持接口登录状态的方法,方便自己回顾。
1.简单粗暴式。
此方法比较小白,前提是已经通过fiddler抓包等方式拿到了cookie,然后直接塞进去。
import requests
trainsUrl ='http://XXX.com/trains'
headers = {
"Content-Type":"application/json;charset=UTF-8",
}
cookies = {
"XXXthor":"XXXXXX105a42"
}
prames = {
'depStationId':'1',
'arrStationId':'2',
'goDate':'1538100286000'
}
res = requests.get(url=trainsUrl, cookies=cookies, params=prames, headers=headers).json()
2.从登录接口获取
import requests
loginUrl ="http://XXX.com/login"
data1 = {
"userName":"157XXXX",
"authCode":"",
"userPwd":"XXXX"
}
headers = {
"Content-Type":"application/json;charset=UTF-8"
}
#运行登录接口
loginRes = requests.post(url=loginUrl, json=data1, headers=headers)
trainsUrl ='http://XXX.com/trains'
parames = {
'depStationId':'1',
'arrStationId':'2',
'goDate':'1538100286000'
}
#运行trainsUrl接口时,从loginRes中获取cookies
res = requests.get(url=trainsUrl, params=parames, cookies=loginRes.cookies).json()
这种方式是先运行登录接口,然后从loginRes中获取cookies,以供后续接口使用。
3.使用会话对象保持登录---摘自网络
import requests
# Session 会话对象
# 会话对象让你能够跨请求保持某些参数。它也会在同一个 Session 实例发出的所有请求之间保持 cookie
# 会话对象具有主要的 Requests API 的所有方法。你可以当成 Request去使用
sessionRequest = requests.session() #实例化会话对象
loginUrl ="http://XXX.com/login"
data = {
"userName":"157XXXX",
"authCode":"",
"userPwd":"XXX"
}
headers = {
"Content-Type":"application/json;charset=UTF-8"
}
#第二次请求的url
trainsUrl ='http://XXX/trains'
parames = {
'depStationId':'1',
'arrStationId':'2',
'goDate':'1538100286000'
}
#登录
resp = sessionRequest.post(url=loginUrl , json=data, headers=headers)
#请求trains接口
trainsResp = sessionRequest.get(url=trainsUrl, params=parames)