我正試圖創建一個Python程序,使用我的ID和密碼登錄到我的大學的網站。這是登錄的正式頁面:https://webapp.pucrs.br/consulta/HTTP POST和GET使用Cookie進行身份驗證在Python中
您可能注意到,這兩個字段分別命名爲pr1和pr2。該頁面使用POST發送數據。此外,在加載頁面時會下載一個cookie,它是一個包含隨機值的JSESSIONID,據我所知,您必須返回POST方法的標題以驗證登錄。
我寫了下面的代碼,但GET方法的返回頁面顯示「會話未初始化」,可能導致cookie未正確發回。
from urllib2 import Request, build_opener, HTTPCookieProcessor, HTTPHandler
import httplib, urllib, cookielib, Cookie, os
conn = httplib.HTTPConnection('webapp.pucrs.br')
#COOKIE FINDER
cj = cookielib.CookieJar()
opener = build_opener(HTTPCookieProcessor(cj),HTTPHandler())
req = Request('http://webapp.pucrs.br/consulta/principal.jsp')
f = opener.open(req)
html = f.read()
for cookie in cj:
c = cookie
#FIM COOKIE FINDER
params = urllib.urlencode ({'pr1':111049631, 'pr2':<pass>})
headers = {"Content-type":"text/html",
"Set-Cookie" : "JSESSIONID=70E78D6970373C07A81302C7CF800349"}
# I couldn't set the value automaticaly here, the cookie object can't be converted to string, so I change this value on every session to the new cookie's value. Any solutions?
conn.request ("POST", "/consulta/servlet/consulta.aluno.ValidaAluno",params, headers) # Validation page
resp = conn.getresponse()
temp = conn.request("GET","/consulta/servlet/consulta.aluno.Publicacoes") # desired content page
resp = conn.getresponse()
print resp.read()
我在哪裏放這個cookie,以便登錄身份驗證?
您可以使用會話自動處理cookie。從[docs](http://docs.python-requests.org/en/latest/user/advanced/#session-objects):* Session對象允許您在請求中保留某些參數。它還會在Session實例的所有請求中保持cookie。* – 2012-04-20 15:15:08
@PiotrDobrogost很酷,謝謝!代碼看起來更好。 – jorgeca 2012-04-20 15:33:44
現在,你可以讓你的答案更好... – 2012-04-20 15:52:47