2

请看下面的 python代码片段:

import cookielib, urllib, urllib2

def login(username, password):
    cookie_jar = cookielib.LWPCookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie_jar))
    login = urllib.urlencode({'username': username, 'password': password})
    try:
        login_data = opener.open("http://www.example.com/login.php", login).read()
    except IOError:
        return 'Network Error'

    # on successful login the I'm storing the 'SESSION COOKIE'
    # that the site sends on a local file called cookie.txt

    cookie_jar.save('./cookie.txt', True, True)
    return login_data

# this method is called after quite sometime
# from calling the above method "login" 

def re_accessing_the _site():
    cookie_jar = cookielib.LWPCookieJar()

    # Here I'm re-loading the saved cookie
    # from the file to the cookie jar

    cookie_jar.revert('./cookie.txt', True, True)

    # there's only 1 cookie in the cookie jar
    for Cookie in cookie_jar:
        print 'Expires : ', Cookie.expires  ## prints None
        print 'Discard : ', Cookie.discard  ## prints True , means that the cookie is a
                                            ## session cookie
        print 'Is Expired : ', Cookie.is_expired()  ## prints False

    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie_jar))
    try:
        data = opener.open("http://www.example.com/send.php")

        # Sometimes the opening fails as the cookie has expired
        # & sometimes it doesn't. Here I want a way to determine
        # whether the (session) cookie is still alive

    except IOError:
        return False
    return True

首先,我调用方法login并将检索到的 cookie(它是一个会话 cookie )保存到一个名为cookie.txt的本地文件中。接下来很长一段时间(15-20 分钟)我正在调用另一种方法re_accessing_the _site。这次我还将之前保存的 cookie 重新加载到 cookie jar 中。有时它工作正常,但有时它阻止我访问(因为会话 cookie 已过期)。所以我只需要一种方法来检查 cookie 在通话期间是否还活着......

4

0 回答 0