Cookie authentication for interface automation

Use the bookstore website as an interface to automate hand practice projects
. If there is no interface document, just grab it with bare hands. The goal is to log in to the website -> enter my bookshelf to query the contents of the bookshelf

After logging in, the login interface and the refreshToken interface are requested. Refresh can be ignored. After login is passed in username and password, it will return the token hm
.

insert image description here

Then the token is renamed to Authorization, which will be added to the cookie of heders as the request header of the bookshelf interface

insert image description here

The first thing I thought about was that requests get the cookies of the login interface, and then assign the obtained cookies to the cookies in the headers, but an error is reported

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'>

The question becomes how to turn the dictionary into a key-value pair connected with '=', and separate key-value pairs with ';'

Go directly to the code

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)

insert image description here

Guess you like

Origin blog.csdn.net/z12347891/article/details/129597799