Python - using cookies successfully

When I try to use facebook cookies to open a registered facebook account ...

import urllib2, urllib, cookielib 

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

data = urllib.urlencode({'email':'','pass':'swagpassword','login':'Log+In'})
req = urllib2.Request('')
response =, data)
cookie_header = response.headers.get("Set-Cookie")
response =, data) #I open it twice on purpose

if "Logout" in
    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('')
cookie_request.add_header("cookie", cookie_header)

cookie_POST =
cookie_POST =

if "Logout" in
    print("Logged In")


It will print "Logged In" the first time successfully, but when I try to use the cookie, I am not logged in. How can I fix this? (Without using other loaded modules)


source to share

1 answer

Just reuse old instances.


if "Logout" in
    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('')
#cookie_request.add_header("cookie", cookie_header)

cookie_POST =





All Articles