2014-09-21 53 views
3

當我嘗試Facebook的cookie來打開Facebook的登錄帳戶...Python的 - 使用Cookie成功

import urllib2, urllib, cookielib 

jar = cookielib.CookieJar()                               
cookie = urllib2.HTTPCookieProcessor(jar)                                
opener = urllib2.build_opener(cookie) 

data = urllib.urlencode({'email':'[email protected]','pass':'swagpassword','login':'Log+In'}) 
req = urllib2.Request('http://www.facebook.com/login.php') 
response = opener.open(req, data) 
cookie_header = response.headers.get("Set-Cookie") 
response = opener.open(req, data) #I open it twice on purpose 

if "Logout" in response.read(): 
    print("Logged In") 


jar = cookielib.CookieJar() #new instance 
cookie = urllib2.HTTPCookieProcessor(jar) #new instance 
opener = urllib2.build_opener(cookie) #new instance 

cookie_request = urllib2.Request('http://www.facebook.com/login.php') 
cookie_request.add_header("cookie", cookie_header) 

cookie_POST = opener.open(cookie_request) 
cookie_POST = opener.open(cookie_request) 

if "Logout" in cookie_POST.read(): 
    print("Logged In") 

這將打印「登錄」,首次成功,但是當我嘗試使用cookie ,我不會登錄。我該如何解決這個問題? (不使用其他下載的模塊)

回答

2

只重用舊實例。

.... 

if "Logout" in response.read(): 
    print("Logged In") 

#jar = cookielib.CookieJar() #new instance 
#cookie = urllib2.HTTPCookieProcessor(jar) #new instance 
#opener = urllib2.build_opener(cookie) #new instance 

cookie_request = urllib2.Request('http://www.facebook.com/login.php') 
#cookie_request.add_header("cookie", cookie_header) 

cookie_POST = opener.open(cookie_request) 

... 
+0

謝謝哈哈,這樣就意味着揭幕戰才能再次使用它存儲的cookie,謝謝 – user3818650 2014-09-21 05:46:20

+1

@ user3818650,'CookieJar'保持餅乾,除非你清除它們。只要您使用使用cookie處理器創建的開放,「HTTPCookieProcessor」負責使用cookie jar。 – falsetru 2014-09-21 05:49:42