python:保存cookie为文本,下次调用

上一篇 / 下一篇  2011-08-29 12:54:46 / 个人分类:python

def login():       
    """ 设置cookie"""
    cookiefile ="./cookies.txt"   
    cookies = cookielib.MozillaCookieJar(cookiefile)
    try:
        """加载已存在的cookie,尝试此cookie是否还有效"""
        cookies.load(ignore_discard=True, ignore_expires=True)
    except Exception:
#        print Exception.message,e
        """加载失败,说明从未登录过,需创建一个cookie kong 文件"""
        cookies.save(cookiefile,ignore_discard=True, ignore_expires=True)

    """将cookie带入到open中"""
    pener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies))
   
    """"loginprofile"""
    url="http://"+Domain+"/core/loginprofile"
    dada=urllib.urlencode({"profile":profile,"password":password})
    """用带有cookie文件的open打开url"""
    response = opener.open(urllib2.Request(url),dada)
    html=response.read()
    root=readXML(html)
    result=root.find("command/result")
    secretqn=root.find("command/message")
#    print result.text,secretqn
    if result.text=='0':
        print root.find("command/message").text
        return -1
    if result.text=='1':
       """打开能获取cookie的页面后,保存该页面有内容的cookie,比如登录成功后保存登录成功后的cookie"""
        cookies.save(cookiefile,ignore_discard=True, ignore_expires=True)
        response.close()
        return cookies #保存成功后将cookie参数传出。
其他地方调用:
cookies=login()
inputValue={a:"b0",c:"dd"}
url='www.wuling.com/login'
opener =urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies))
dada=urllib.urlencode(inputValue)
response = opener.open(urllib2.Request(url),dada)



本函数中用的cookie是MozillaCookieJar的一个实例,MozillaCookieJar继承自FileCookieJar,FileCookieJar也有save方法,但是FileCookieJar是基类(subclasses),只提供接口,没有提供实现,所以要想保存cookie,要么用MozillaCookieJar的save方法,要么用LWPCookieJar的save.
FileCookieJar.save原型:
    def save(self, filename=None, ignore_discard=False, ignore_expires=False):
        """Save cookies to a file."""
        raise NotImplementedError()
MozillaCookieJar.save原型:
   def save(self, filename=None, ignore_discard=False, ignore_expires=False):
        if filename is None:
            if self.filename is not None: filename = self.filename
            else: raise ValueError(MISSING_FILENAME_TEXT)

        f = open(filename, "w")
        try:
            f.write(self.header)
            now = time.time()
            for cookie in self:
                if not ignore_discard and cookie.discard:
                    continue
                if not ignore_expires and cookie.is_expired(now):
                    continue
                if cookie.secure: secure = "TRUE"
                else: secure = "FALSE"
                if cookie.domain.startswith("."): initial_dot = "TRUE"
                else: initial_dot = "FALSE"
                if cookie.expires is not None:
                    expires = str(cookie.expires)
                else:
                    expires = ""
                if cookie.value is None:
                    # cookies.txt regards 'Set-Cookie: foo' as a cookie
                    # with no name, whereas cookielib regards it as a
                    # cookie with no value.
                    name = ""
                    value = cookie.name
                else:
                    name = cookie.name
                    value = cookie.value
                f.write(
                    "\t".join([cookie.domain, initial_dot, cookie.path,
                               secure, expires, name, value])+
                    "\n")
        finally:
            f.close()



LWPCookieJar.save原型:
   def save(self, filename=None, ignore_discard=False, ignore_expires=False):
        if filename is None:
            if self.filename is not None: filename = self.filename
            else: raise ValueError(MISSING_FILENAME_TEXT)

        f = open(filename, "w")
        try:
            # There really isn't an LWP Cookies 2.0 format, but this indicates
            # that there is extra information in here (domain_dot and
            # port_spec) while still being compatible with libwww-perl, I hope.
            f.write("#LWP-Cookies-2.0\n")
            f.write(self.as_lwp_str(ignore_discard, ignore_expires))
        finally:
            f.close()


TAG:

 

评分:0

我来说两句

Open Toolbar