python獲取服務器響應cookie

總結

調試網站獲取cookies時請查看,r.header和r.request.header這兩個屬性,因爲cookie說不準出現在他們倆誰裏面。

先貼一個代碼

import re
import requests
from bs4 import BeautifulSoup
def printHeaders(headers):
    for h in headers:
        print(h+" : "+headers[h] + '\r\n')

def printCookies(cookies):
    for h in cookies:
        print(h+" : "+cookies[h] + '\r\n')

def loginFw(id,password):
    url = "http://xxxxx/login.asp" 
    try:
        headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:55.0) Gecko/20100101 Firefox/55.0',
                   'Host':'www.xxx.org',
                   'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                   'Accept-Language':'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
                   'Accept-Encoding':'gzip, deflate',
                   'Content-Type':'application/x-www-form-urlencoded',
                   'Referer':'http://xxx/login.asp',
                   'Connection':'keep-alive',
                   }
        params = {"Reglname":id,"reglpassword":password}
        r = requests.post(url,data=params,headers=headers)
        printHeaders(r.request.headers) #服務器返回的cookie需要用r.request裏的headers來獲取
        printHeaders(r.headers) #這裏是獲取不到服務器返回的cookie的

        r.encoding = 'utf-8'

        return r.text
    except Exception as e:
        print("登陸錯誤:"+str(e))




ret = loginFw("[email protected]","xxx")
#print(ret)

事情經過

 事情的發生是這樣的,今天我在調試一個網站的模擬登陸,但是怎麼調試都調試不出來這個網站返回的cookie(因爲我是用r.headers來獲取cookies的),後來我就在想是不是我的請求頭沒有設置正確,然後我就遍歷了r.request.headers,然後這個變量如實的打印了我的請求頭的信息,但是我仔細一看cookie怎麼出現了變化,咦,這不就是我需要的響應cookie嗎!
 難道是我對r.request這個對象的理解出錯了嗎?以前我一直認爲這個對象裏面存儲的是我請求發出去的信息,現在怎麼會出現響應cookie呢?
 就在我百撕不得其解的時候,我去翻閱了requests庫的官方文檔關於respond對象中包含的request的解釋,它上面寫着“The PreparedRequest object to which this is a response.”(表示看不到什麼意思,百度翻譯也翻譯不清楚),咦,好像是和響應有關啊,看來應該是我的理解出現了錯誤。

更好的解決方案

  那當然是用requests提供的"會話對象",他能夠自動的保留請求所獲取的參數。
  具體請跳轉傳送門:http://cn.python-requests.org/zh_CN/latest/user/advanced.html#request-and-response-objects

後來

  後來我發現原來是因爲我在請求頭裏面寫了“Host”,“Referer”,導致Cookie出現異常的原因,所以以後不要隨便寫這兩個參數了,要寫就照着封包裏的寫。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章