python 獲取cookie,發送請求


獲取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

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM