views:

20

answers:

1

I am working off of the example code given by Anthony Briggs. However it doesn't seem to save the cookies back into the defined cookie file.

My modified code. I switched to using LWPCookieJar because its supposedly fully compatible and also removed the login code into a separate function so that I can first test if I am login, and then if not, call the login functionality.

If I login with an object, get new cookies, save them, and then create a new object loading the same file, it reverts to the cookies stored before login.

Test Code:

facebookObject = FacebookBrowser(cookie_filename)
#check if authenticated
success=myAuthenticationTest(facebookObject)
if not success:
    facebookObject.setupUser(facebookObject.login, facebookObject.password, cookie_filename)
    resp = facebookObject.opener.open(testurl) #new cookies should be set

    facebookObject.cj.save(cookie_filename)
    saved_cookies =  facebookObject.cj

    facebookObject2 = FacebookBrowser(cookie_filename)
    newly_loaded_cookies = facebookObject2.cj


    #saved_cookies != newly_loaded_cookies

Class Code:

class FacebookBrowser(object):

  def __init__(self,cookie_filename):
    """ Start up... """
    self.login = xxxxx
    self.password = yyyyyy
    self.cookie_filename = cookie_filename

    self.cj = cookielib.LWPCookieJar(cookie_filename)
    if os.access(cookie_filename, os.F_OK):
        self.cj.load()

    self.opener = urllib2.build_opener(
        urllib2.HTTPRedirectHandler(),
        urllib2.HTTPHandler(debuglevel=0),
        urllib2.HTTPSHandler(debuglevel=0),
        urllib2.HTTPCookieProcessor(self.cj)
    )

    self.opener.addheaders = [
        ('User-agent', ('Mozilla/5.0 (Windows; U; Windows NT 6.1; he; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3'))
    ]


  def setupUser(self, login, password,cookie_filename):

    # need this twice - once to set cookies, once to log in...
    self.loginToFacebook()
    self.loginToFacebook()

    self.cj.save()

    self.opener = urllib2.build_opener(
        urllib2.HTTPRedirectHandler(),
        urllib2.HTTPHandler(debuglevel=0),
        urllib2.HTTPSHandler(debuglevel=0),
        urllib2.HTTPCookieProcessor(self.cj)
    )

    self.cj.save()


  def loginToFacebook(self):
    """
    Handle login. This should populate our cookie jar.
    """
    login_data = urllib.urlencode({
        'email' : self.login,
        'pass' : self.password,
    })
    response = self.opener.open("https://login.facebook.com/login.php", login_data)
    return ''.join(response.readlines())
A: 

I just read on another forum that I needed to set ignore_discard=True in all the .save() and .load() methods.

JiminyCricket