我正在尝试创建一个使用我的 ID 和密码登录到我大学网站的 python 程序。这是登录的正式页面:https ://webapp.pucrs.br/consulta/
您可能会注意到,这两个字段名为 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 放在哪里,以便对登录进行身份验证?