python登陸網頁并處理網站session和cookie
這是一個python通過urllib直接登陸網站,并處理網站的session和cookie
import cookielib, urllib, urllib2login = 'ismellbacon123@yahoo.com' password = 'login'
Enable cookie support for urllib2
cookiejar = cookielib.CookieJar() urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))
Send login/password to the site and get the session cookie
values = {'login':login, 'password':password } data = urllib.urlencode(values) request = urllib2.Request("http://www.imdb.com/register/login", data) url = urlOpener.open(request) # Our cookiejar automatically receives the cookies page = url.read(500000)
Make sure we are logged in by checking the presence of the cookie "id".
(which is the cookie containing the session identifier.)
if not 'id' in [cookie.name for cookie in cookiejar]: raise ValueError, "Login failed with login=%s, password=%s" % (login,password)
print "We are logged in !"
Make another request with our session cookie
(Our urlOpener automatically uses cookies from our cookiejar)
本文由用戶 g2b4 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!