Cookie Jar Lib不会将cookie保存回文件?

时间:2010-09-02 19:02:36

标签: python cookies urllib2

我正在使用Anthony Briggs.给出的示例代码。但是它似乎没有将cookie保存回定义的cookie文件中。

我修改过的代码。我切换到使用LWPCookieJar,因为它应该是fully compatible并且还将登录代码删除到一个单独的函数中,以便我可以首先测试我是否登录,然后如果没有,则调用登录功能。

如果我使用对象登录,获取新cookie,保存它们,然后创建一个加载同一文件的新对象,它将恢复为登录前存储的cookie。

测试代码:

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 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())

1 个答案:

答案 0 :(得分:2)

我刚刚阅读another forum,我需要在所有.save()和.load()方法中设置ignore_discard=True