Python urllib2 cookie将打印但不会保存

时间:2014-05-29 01:25:17

标签: python cookies urllib2

我可以遍历HTTPS响应的cookie但我无法将它们保存到磁盘。为什么不呢?

cookies = cookielib.LWPCookieJar('mycookies.txt')

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, user, password)

handlers = [
    HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman),
    urllib2.HTTPHandler(),
    urllib2.HTTPSHandler(),
    urllib2.HTTPCookieProcessor(cookies)
    ]

headers = {
    /* headers go here */
    }

# create and install the opener
opener = urllib2.build_opener(*handlers)

def fetch(uri):
    req = urllib2.Request(uri, headers)
    return opener.open(uri)

def dump():
    for cookie in cookies:
        print cookie.name, cookie.value


# retrieve the result
resp = fetch(url)
dump()
cookies.save()

当我运行代码时,响应中的cookie会打印到控制台,但是当我打开mycookies.txt文件时,我看到的只是#LWP-Cookies-2.0

1 个答案:

答案 0 :(得分:0)

想出来。最后一行需要看起来像这样:

cookies = cookielib.LWPCookieJar('myaxis.cookies')