python-requests模塊-獲取cookie以及使用cookie


參考鏈接

https://www.cnblogs.com/liuzhzhao/p/12114453.html

思路:先調用登錄接口獲取cookie,再將獲取到的cookie用到其他的接口調用中去

登錄接口需要賬號,密碼,驗證碼,驗證碼需要到redis中獲取

#coding:utf-8
import redis
import os
import requests
host = ''
port = 11111
password = '123456'
#建立一個redis連接池,然后作為參數 Redis,這樣就可以實現多個 Redis 實例共享一個連接池
pool = redis.ConnectionPool(host=host,port=port,password=password)
r = redis.Redis(connection_pool=pool)
def getKey_fRedis(key):
'''
從redis中獲取指定key的value值
'''
value = r.get(key)
return value

def get_code(key):
'''
獲取驗證碼
'''
if getKey_fRedis(key) == None:
#index = requests.get("http://ip:port/url/")
print "step1"
os.system("curl http://ip:port/url/")
#code = getKey_fRedis(key).replace("\"",'')
#return code

import requests

def login(key):
login_url = 'http://ip:port/login'
headers = {
"Accept": "application/json, text/javascript, */*; q=0.01"
}
body = {
"username": "test",
"password": "1234567",
"vrifyCode": get_code(key)
}
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))

def get_data(key,get_data_url):
ck = login(key)
cookie = {
'_wafuid': ck["_wafuid"],
'JSESSIONID': ck["JSESSIONID"],
' _wafuid': '99627601'
}
res = requests.get(url=get_data_url, cookies=cookie)
print res.text


if __name__=="__main__":
key = 'test'
get_data_url = 'http://ip:port/url'
#get_data(key, get_data_url)
#get_code(key)
get_code(key)
print getKey_fRedis(key)


免責聲明!

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



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