3

When I would try facebook cookies to open a logged account on facebook...

import urllib2, urllib, cookielib 

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

data = urllib.urlencode({'email':'user@email.com','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")

It would print "Logged In" the first time successfully, but when I try using the cookie, I would not be logged in. How can I fix this? (Without using other downloaded modules)

user3818650
  • 581
  • 1
  • 7
  • 19

1 Answers1

2

Just reuse the old instances.

....

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)

...
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • Thank you haha, so that means the opener can use its stored cookies again, thank you – user3818650 Sep 21 '14 at 05:46
  • 1
    @user3818650, `CookieJar` keeps cookies unless you clear them. `HTTPCookieProcessor` takes care of using the cookie jar as long as you use opened created with the cookie processor. – falsetru Sep 21 '14 at 05:49