Python中用requests处理cookies的3种方法

在接口测试中,大多数项目的接口是需要登录后进行操作的,经常用到requests库进行模拟登录及登录后的操作,下面是我不断踩坑后总结出来的关于登录凭证cookies的3种操作方法。

一. 用 requests.utils.dict_from_cookiejar() 把返回的cookies转换成字典

  1. 处理cookies:

import requests

def login():
login_url = 'http://www.xxx.com/login
headers = {
"Accept": "application/json, text/javascript, */*; q=0.01"
}
body = {
"usercode": "liuzz05@****.com",
"password": "123456"
}
try:
res = requests.post(url=login_url, headers=headers, data=body)
cookies = res.cookies

cookie = requests.utils.dict_from_cookiejar(cookies)

return cookie
except Exception as err:
print('获取cookie失败:\n{0}'.format(err))

 

2. 使用cookie:

import requests
 
 def get_data():
     cookie = login()
     res = requests.get(url=get_data_url, cookies=cookie)
     print(res.text)

二. 遍历cookies的键值,拼接成cookie格式

  1. 处理cookies:

import requests

def login():
login_url = 'http://www.xxx.com/login
headers = {
"Accept": "application/json, text/javascript, */*; q=0.01"
}
body = {
"usercode": "liuzz05@****.com",
"password": "123456"
}
try:
res = requests.post(url=login_url, headers=headers, data=body)
cookies = res.cookies.items()

cookie = ''
for name, value in cookies:
cookie += '{0}={1};'.format(name, value)

return cookie
except Exception as err:
print('获取cookie失败:\n{0}'.format(err))

 

2. 使用cookie:

import requests

def get_data():
cookie = login()
headers = {
"cookie": cookie
}
res = requests.get(url=get_data_url, headers=headers)
print(res.text)

 

三. 直接拼接cookies,这种方法比较傻,前提是要知道cookies的键

  1. 处理cookies:

import requests

def login():
login_url = 'http://www.xxx.com/login
headers = {
"Accept": "application/json, text/javascript, */*; q=0.01"
}
body = {
"usercode": "liuzz05@****.com",
"password": "123456"
}
try:
res = requests.post(url=login_url, headers=headers, data=body)
cookies = res.cookies

phpsessid = cookies['phpsessid']
env_orgcode = cookies['env_orgcode']
acw_tc = cookies['acw_tc']
aliyungf_tc = cookies['aliyungf_tc']
last_env = cookies['last_env']

cookie = 'phpsessid={0};env_orgcode={1};acw_tc{2};aliyungf_tc={3};last_env={4}'.format(
phpsessid, env_orgcode, acw_tc, aliyungf_tc, last_env
)

return cookie
except Exception as err:
print('获取cookie失败:\n{0}'.format(err))

 

2. 使用cookie:

import requests

def get_data():
cookie = login()
headers = {
"cookie": cookie
}
res = requests.get(url=get_data_url, headers=headers)
print(res.text)

posted @ 2023-12-04 11:00  ReturnHome  阅读(1168)  评论(0编辑  收藏  举报