2014-09-19 116 views
2

我無法獲得一個cookie,將它傳遞給我的參數列表,然後使用請求lib發佈該cookie。需要requests.get一個cookie(ASP.NET_SessionID),然後requests.post,該cookie作爲參數

我已經用Burpsuite和postId來捕獲該文章,其中一個參數參見下面的截圖。對於網頁 http://imgur.com/OuRi4bI

的源代碼是在下面 http://imgur.com/TLTgCjc

我的代碼截圖包含如下:

import requests 
import cookielib 
import sys 
from bs4 import BeautifulSoup 

print "Enter the url", 
url = raw_input 
print url 
r = requests.get(url) 
c = r.content 
soup = BeautifulSoup(c) 

#Finding Captcha 
div1 = soup.find('div', id='Custom') 
comment = next(div1.children) 
captcha = comment.partition(':')[-1].strip() 
print captcha 

#Finding viewstate 
viewstate = soup.findAll("input", {"type" : "hidden", "name" : "__VIEWSTATE"}) 
v = viewstate[0]['value'] 
print v 

#Finding eventvalidation 
eventval = soup.findAll("input", {"type" : "hidden", "name" : "__EVENTVALIDATION"}) 
e = eventval[0]['value'] 
print e 

# Get Cookie (this is where I am confused), and yes I have read through the Requests and BS docs 
s = r.cookies 
print s # Prints the class call but I don't get anything I can pass as a parameter 

#Setting Parameters 
params = { 
      '__VIEWSTATE' : v, 
      'txtMessage' : 'test', 
      'txtCaptcha' : captcha, 
      'cmdSubmit' : 'Submit', 
      '__EVENTVALIDATION' : e 
      #Need ASP.NET_SessionId Key : Value here 
} 

#Posting 
requests.post(url, data=params) 

print r.status_code 

所以要清楚,我想,當我拿的SessionID連接到Web服務器並將其用作參數發佈到此留言板。這是針對沙盒虛擬機上的實驗室,而不是實況網站。這是我第一次用Python寫一篇文章,所以如果我錯了,我已經做了最好的,我可以通過Lib文檔和其他網站閱讀。

謝謝!

回答

2

將「s」作爲參數傳遞給您的帖子。

s = r.cookies 
print s # Prints the class call but I don't get anything I can pass as a parameter 

您需要傳遞cookie作爲名爲「cookies」的參數。在https://github.com/kennethreitz/requests/blob/master/requests/sessions.py的源代碼中,它表示cookie可以是CookieJar或包含要傳遞的cookie的字典。

就你而言,將你的cookies複製到下一篇文章比較容易,不需要將它們轉換爲字典。

設置參數

params = { 
     '__VIEWSTATE' : v, 
     'txtMessage' : 'test', 
     'txtCaptcha' : captcha, 
     'cmdSubmit' : 'Submit', 
      '__EVENTVALIDATION' : e 
      #Need ASP.NET_SessionId Key : Value here 
} 

#Posting 
requests.post(url, data=params,cookies=s) 

不過,我強烈建議您使用requests.Session()對象。

session = requests.Session() 
session.get(url) 
session.get(url2) 
#It will keep track of your cookies automatically for you, for every domain you use your session on . Very handy in deed, I rarely use requests.get unless I don't care at all about cookies. 
+0

這看起來與我寫的代碼有關嗎?我是否調用會話對象並運行對象的get和post,以便所有cookie和參數保持持久性?我正在學習請求庫。 – Phi 2014-09-19 16:00:47

+0

是的,基本上,而不是調用requests.get() 您將首先創建一個會話。 session = requests.Session() 然後你會調用你試圖調用的同一個方法,但會話對象。 會話只會跟蹤您的Cookie而不是您的參數。 YOu將需要根據您希望的每一篇文章更改參數,並讓您想要製作。 – IAlwaysBeCoding 2014-09-19 16:02:47

+0

非常感謝,讓我試試看,我會迴圈。 – Phi 2014-09-19 16:04:42

相關問題