2011年1月3日月曜日

python HTTPクライアントでログイン(POST)処理

特にSBI証券でのリダイレクト関連でセッションが切れることへの対策
が全くわかりません。
ログイン後の処理は試行錯誤中。誰か教えてくれんかなあ。



""" ログイン用の設定 URLやパスワードなど"""
url_string = "ログイン先URL"
form_fields = {
"userName": "*****",
"loginPwdSet": "*****",
'x':'3',
'y':'15'
}
""" POSTでクッキー関連の設定を済ませたopenerを作成 """
def __init__():
cookies = cookielib.CookieJar()
cookie_handler = urllib2.HTTPCookieProcessor(cookies)
redirect_handler = urllib2.HTTPRedirectHandler()
return urllib2.build_opener(redirect_handler, cookie_handler)

""" openerを用いてログイン処理を行う。 """
def login(opener):
try:
form_data = urllib.urlencode(form_fields)
request = urllib2.Request(url_string, form_data)
res = opener.open(request)
return res.read()

except urllib2.HTTPError, e:
print "error has occurred\n"
print e.msg, e.code
except urllib2.URLError, e:
print "error has occurred\n"
print e

def main():
opener = __init__()
response = login(opener)
if __name__ == '__main__':
main()

0 件のコメント: