首页 > 技术文章 > python 获取cookie,发送请求

apple2016 2020-12-31 14:37 原文

获取cookie思路:

1、确认登录login接口,及登录所需参数(包括用户名、密码、uuid等参数);

2、确认uuid等参数的获取接口(一般是get请求);

3、凭借uuid等参数向login接口发起请求,获取响应报文中的cookie(不同的网站平台可能表示方法不一样,需区别对待);

示例代码:

# -*- coding:UTF-8 -*-
import json,chardet,requests
import os
import httplib
httplib.HTTPConnection._http_vsn = 10
httplib.HTTPConnection._http_vsn_str = 'HTTP/1.0'

#获取uuid
uuid_url="http://ip:7924/alpha/captchaImage"
uuidresponse=requests.get(uuid_url)#返回response对象
uuidresponse_json=uuidresponse.text #获取响应json报文
uuidresponse_dict=json.loads(uuidresponse_json,encoding="utf-8") #json响应报文转换为字典类型,方便后续数据处理
uuid=uuidresponse_dict['uuid']#从响应中获取uuid
print uuid

#登录并获取cookie
login_url="http://ip:7924/alpha/login?username=XXXX@hq.cmcc&password=admin123&code=1111&uuid="+uuid
login_head={"Content-Type": "application/json; charset=UTF-8", "Connection": "keep-alive"}
login_body={"username":"XXXX@hq.cmcc","password":"admin123","code":"1111","uuid":uuid}

print login_url
print login_body

try:
    res = requests.post(url=login_url, headers=login_head, data=login_body)
    loginresponse_json=res.text
    loginresponse_dict=json.loads(loginresponse_json,encoding="utf-8")
    token = loginresponse_dict['token']
    print 'get token=', token
    cookie ='Bearer '+token
    print 'get cookie=',cookie
    
except Exception as err:
    print '获取cookie失败!',err
    
#保存cookie到文件中
tokenpath=os.path.abspath(os.path.dirname(os.path.dirname(__file__)))+'\\'
#tokenpath=os.path.abspath(os.path.dirname(os.getcwd()))+'\\'
cookiefiledata='NewCookie\r\n'+cookie+'\r\n'
with open(tokenpath+"tianbaoNewCookie.txt",'wb') as f:
    f.write(cookiefiledata)
    
#使用cookie  
filepath = os.path.abspath(os.path.dirname(__file__))+'\\'
print 'filepath=',filepath

request_url="http://ip:7924/alpha/light/todo/query/todoTaskList"
request_dictdata={'officeType':'1001','busiType':None,'status':None,'startTime':'','endTime':'','pageNum':1,'pageSize':500,'find':'压测表单业务','officeTypes':['1001'],'busiTypes':[]}

print type(request_dictdata)

requestJSONdata=json.dumps(request_dictdata)

head = {"Content-Type": "application/json; charset=UTF-8", "Connection": "close","Authorization": cookie}

print '>>>>>>requestJSONdata:\n',requestJSONdata

try:
    r = requests.post(request_url,data=requestJSONdata,headers=head)
except Exception as e:
    print '【error: 】',e
    raise Exception(e)


responsedata=r.text
print "get the status: ",r.status_code
        

load_dict=json.loads(responsedata,encoding="utf-8")
print '<<<<<<<responsedata:\r\n',load_dict

  

推荐阅读