requests之session會話管理,只有這一篇我看懂了!!
阿新 • • 發佈:2021-01-31
技術標籤:Python介面自動化cookiesessionrequests會話管理
session會話管理
如何理解http協議裡的無狀態
- 比如商場購物車,你把東西放到購物車,如果http協議的話,重新整理頁面,購物車就為空了
- 簡單理解就是http重新整理後就不會記得你之前做了什麼
為什麼用到cookie
- web2.0互動時代,所以就引用cookie和seesion來記錄狀態,比如登入
為什麼要用到會話管理?
- 如果很多個介面都要用到cookies,如果每次都要手動傳cookies是不是很麻煩???
手動傳入cookie
- 請求購物車介面(沒有登入的情況),如果沒傳入cookie,就無法檢視到購物車裡的商品(就是剛剛說的httpt是無狀態的)
- 請求購物車介面時,必須手動帶上cookie引數,才能檢視到購物車內的商品
- 那麼有沒有一種方式,訂單介面自動能帶上cookeis?不用手動去傳cookies!
# -*- coding: utf-8 -*-
# @Author : 碼上開始
import requests
# 登入介面
log_url = "http://shopxo.hctestedu.com/index.php?s=/index/user/login.html"
# 登入參靈敏
data = {"accounts": "laozhu",
"pwd": "123456"}
# 頭部資訊
head = {"X-Requested-With": "XMLHttpRequest"}
login_response = requests.post(log_url, data=data, headers=head)
# 獲取cookie,傳給下面訂單介面
cookie = login_response.cookies
# 訂單介面
order_url = "http://shopxo.hctestedu.com/index.php?s=/index/cart/index.html"
order_response = requests.get(order_url, cookies=cookie)
print(order_response.text)
session會話管理
- 可以保持會話,將cookies等值自動傳到下一個介面(注意:是自動傳到下一個介面)
- 換句話說,就是不用手動去傳cookie的值
# -*- coding: utf-8 -*-
# @Author : 碼上開始
import requests
# 登入介面
log_url = "http://shopxo.hctestedu.com/index.php?s=/index/user/login.html"
# 登入參靈敏
data = {"accounts": "laozhu",
"pwd": "123456"}
# 頭部資訊
head = {"X-Requested-With": "XMLHttpRequest"}
# 例項化session對像
session = requests.session()
login_response = session.post(log_url, data=data, headers=head)
# 訂單介面
order_url = "http://shopxo.hctestedu.com/index.php?s=/index/cart/index.html"
# 不用手動傳入cookies值,因為session自動帶上了
order_response = session.get(order_url)
print(order_response.text)
# 列印cookies
print(session.cookies)