Python中用requests处理cookies的3种方法
Posted 王昭君的昭
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python中用requests处理cookies的3种方法相关的知识,希望对你有一定的参考价值。
在接口测试中,大多数项目的接口是需要登录后进行操作的,经常用到requests库进行模拟登录及登录后的操作,下面是我不断踩坑后总结出来的关于登录凭证cookies的3种操作方法。
一. 用 requests.utils.dict_from_cookiejar() 把返回的cookies转换成字典
1. 处理cookies:
1 import requests 2 3 def login(): 4 login_url = ‘http://www.xxx.com/login 5 headers = { 6 "Accept": "application/json, text/javascript, */*; q=0.01" 7 } 8 body = { 9 "usercode": "liuzz05@****.com", 10 "password": "123456" 11 } 12 try: 13 res = requests.post(url=login_url, headers=headers, data=body) 14 cookies = res.cookies 15 16 cookie = requests.utils.dict_from_cookiejar(cookies) 17 18 return cookie 19 except Exception as err: 20 print(‘获取cookie失败: {0}‘.format(err))
2. 使用cookie:
1 import requests 2 3 def get_data(): 4 cookie = login() 5 res = requests.get(url=get_data_url, cookies=cookie) 6 print(res.text)
二. 遍历cookies的键值,拼接成cookie格式
1. 处理cookies:
1 import requests 2 3 def login(): 4 login_url = ‘http://www.xxx.com/login 5 headers = { 6 "Accept": "application/json, text/javascript, */*; q=0.01" 7 } 8 body = { 9 "usercode": "liuzz05@****.com", 10 "password": "123456" 11 } 12 try: 13 res = requests.post(url=login_url, headers=headers, data=body) 14 cookies = res.cookies.items() 15 16 cookie = ‘‘ 17 for name, value in cookies: 18 cookie += ‘{0}={1};‘.format(name, value) 19 20 return cookie 21 except Exception as err: 22 print(‘获取cookie失败: {0}‘.format(err))
2. 使用cookie:
1 import requests 2 3 def get_data(): 4 cookie = login() 5 headers = { 6 "cookie": cookie 7 } 8 res = requests.get(url=get_data_url, headers=headers) 9 print(res.text)
三. 直接拼接cookies,这种方法比较傻,前提是要知道cookies的键
1. 处理cookies:
1 import requests 2 3 def login(): 4 login_url = ‘http://www.xxx.com/login 5 headers = { 6 "Accept": "application/json, text/javascript, */*; q=0.01" 7 } 8 body = { 9 "usercode": "liuzz05@****.com", 10 "password": "123456" 11 } 12 try: 13 res = requests.post(url=login_url, headers=headers, data=body) 14 cookies = res.cookies 15 16 phpsessid = cookies[‘phpsessid‘] 17 env_orgcode = cookies[‘env_orgcode‘] 18 acw_tc = cookies[‘acw_tc‘] 19 aliyungf_tc = cookies[‘aliyungf_tc‘] 20 last_env = cookies[‘last_env‘] 21 22 cookie = ‘phpsessid={0};env_orgcode={1};acw_tc{2};aliyungf_tc={3};last_env={4}‘.format( 23 phpsessid, env_orgcode, acw_tc, aliyungf_tc, last_env 24 ) 25 26 return cookie 27 except Exception as err: 28 print(‘获取cookie失败: {0}‘.format(err))
2. 使用cookie:
1 import requests 2 3 def get_data(): 4 cookie = login() 5 headers = { 6 "cookie": cookie 7 } 8 res = requests.get(url=get_data_url, headers=headers) 9 print(res.text)
以上是关于Python中用requests处理cookies的3种方法的主要内容,如果未能解决你的问题,请参考以下文章
Python爬虫编程思想(22):使用requests网络库上传文件处理Cookie和Session