我正在处理 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)代码:
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())

最佳答案

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

关于python - Cookie Jar Lib 不会将 cookie 保存回文件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3630307/

10-17 00:22