接口自动化之cookie鉴权

读书屋网站作为接口自动化练手项目
没有接口文档,就徒手抓,目标是登录网站->进入我的书架查询书架内容

登录后请求了login接口和refreshToken接口,refresh可以忽略,login传入username和password之后,会返回token
hm开头的cookie是百度自带的,正常用requests是获取不到的,也不用管

在这里插入图片描述

然后token改了个名字叫Authorization,会加到heders的Cookie里,作为书架接口的请求头

在这里插入图片描述

最开始想的是requests获取到login接口的cookies,再把拿到的cookies赋值给headers里的Cookie,但报错

requests.exceptions.InvalidHeader: Header part ({'userClientMarkKey': xxx', 'Authorization': 'xxx'}) from {'Cookie': {'userClientMarkKey': 'xxx', 'Authorization': 'xxx'}} must be of type str or bytes, not <class 'dict'>

问题就变成了如何把字典变成一个键值对用’=‘相连,不同键值对用’;'隔开

直接上代码吧

import requests

s = requests.Session()
#登录接口
res = s.post(url="http://novel.hctestedu.com/user/login",data={
    
    'username':'xxx','password':'xxx'}) # 用户名和密码填自己的
# 获取cookie(字典格式)
cookiejar = res.cookies.get_dict()
print('最初的cookie:',cookiejar)
x = res.json()
print('返回值里有token:',res.json())
print('token的值:',x['data']['token'])
cookiejar['Authorization'] = x['data']['token']
print('加上token之后的cookie:',cookiejar)
# 把字典变成一个键值对用'='相连,不同键值对用';'隔开 的字符串
cookie_string = ';'.join(str(x)+ '='+ str(y) for x,y in cookiejar.items())
headers = {
    
    
    'Cookie': cookie_string
}
#书架接口
booklist = requests.get('http://novel.hctestedu.com/user/listBookShelfByPage?curr=1&limit=10',headers=headers)
print('书架列表:',booklist.text)

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/z12347891/article/details/129597799