Python FileCookieJar.save() 问题

发布于 2024-12-27 02:17:51 字数 1017 浏览 0 评论 0原文

我在尝试使用 FileCookieJarsave 方法将 cookie 保存到文件时遇到问题。这是我的代码:

#!/usr/bin/python
import httplib, cookielib, urllib2, json, time
from datetime import date


class FoN:
    def __init__(self):
            self.cookiefile = "cookies.txt"
            self.cj = cookielib.FileCookieJar(self.cookiefile)
    def login (self, login, password):
            js = json.JSONEncoder().encode({"login":login,"password":password})
            req=urllib2.Request("http://www.example.com/user/login", js)
            res=urllib2.urlopen(req)
            self.cj.extract_cookies(res,req)
            self.cj.save(self.cookiefile, ignore_discard=True)
            f.write ("Login: "+login+", result: "+str(res.read().count("true"))+"\n")
            time.sleep(2)
            return res

所以它在 self.cj.save(self.cookiefile,ignore_discard=True) 处失败,引发 NotImplementedError 异常,这是根据文档的。但我的问题是如何将 cookie 保存到文件中?我什至尝试将代码包含在 try 子句中,但这根本没有帮助。

I have a problem while trying to save cookies to a file using FileCookieJar's save method. Here is my code:

#!/usr/bin/python
import httplib, cookielib, urllib2, json, time
from datetime import date


class FoN:
    def __init__(self):
            self.cookiefile = "cookies.txt"
            self.cj = cookielib.FileCookieJar(self.cookiefile)
    def login (self, login, password):
            js = json.JSONEncoder().encode({"login":login,"password":password})
            req=urllib2.Request("http://www.example.com/user/login", js)
            res=urllib2.urlopen(req)
            self.cj.extract_cookies(res,req)
            self.cj.save(self.cookiefile, ignore_discard=True)
            f.write ("Login: "+login+", result: "+str(res.read().count("true"))+"\n")
            time.sleep(2)
            return res

So it fails at self.cj.save(self.cookiefile, ignore_discard=True) raising NotImplementedError exception, which is according to the documentation. But my question how do I save cookies to the file then? I even tried to include the code in try clause but that didn't help at all.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

半窗疏影 2025-01-03 02:17:51

基本 FileCookieJar 未实现 .save 要进行保存,您应该使用 MozillaCookieJarLWPCookieJar 等子类之一>。

The base FileCookieJar does not implement .save To get saving, you should use one of the subclasses like MozillaCookieJar or LWPCookieJar.

扛起拖把扫天下 2025-01-03 02:17:51

我已将示例代码写入演示:

  • 自动处理cookie:内存中的cookie
  • 自动处理cookie:文件中的cookie
    • 支持两种格式:
      • LWP
      • Mozilla
    • 两种操作
      • 保存到文件
      • 从文件加载

代码:



    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    """
    Function:   【整理】Python中Cookie的处理:自动处理Cookie,保存为Cookie文件,从文件载入Cookie
                http://www.crifan.com/python_auto_handle_cookie_and_save_to_from_cookie_file

    Version:    2013-01-15
    Author:     Crifan
    Contact:    admin (at) crifan.com
    """

    import os;
    import cookielib;
    import urllib2;

    def pythonAutoHandleCookie():
        """
            Demo how to auto handle cookie in Python
                cookies in memory
                cookies in file:
                    save cookie to file
                        LWP     format
                        Mozilla format
                    load cookie from file
        """

        print "1. Demo how to auto handle cookie (in memory)";
        cookieJarInMemory = cookielib.CookieJar();
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJarInMemory));
        urllib2.install_opener(opener);
        print "after init, cookieJarInMemory=",cookieJarInMemory; #after init, cookieJarInMemory= 
        #!!! following urllib2 will auto handle cookies
        demoUrl = "http://www.google.com/";
        response = urllib2.urlopen(demoUrl);
        #here, we already got response cookies
        print "after urllib2.urlopen, cookieJarInMemory=",cookieJarInMemory;
        #after urllib2.urlopen, cookieJarInMemory= , , ]>


        print "2. Demo how to auto handle cookie in file, LWP format";
        cookieFilenameLWP = "localCookiesLWP.txt";
        cookieJarFileLWP = cookielib.LWPCookieJar(cookieFilenameLWP);
        #will create (and save to) new cookie file
        cookieJarFileLWP.save();
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJarFileLWP));
        urllib2.install_opener(opener);
        #!!! following urllib2 will auto handle cookies
        demoUrl = "http://www.google.com/";
        response = urllib2.urlopen(demoUrl);
        #update cookies, save cookies into file
        cookieJarFileLWP.save();
        #for demo, print cookies in file
        print "LWP cookies:";
        print open(cookieFilenameLWP).read(os.path.getsize(cookieFilenameLWP));
        # #LWP-Cookies-2.0
        # Set-Cookie3: PREF="ID=34c1415b570a93ae:FF=0:NW=1:TM=1358236121:LM=1358236121:S=gEVVojW4x37ht5n-"; path="/"; domain=".google.com"; path_spec; domain_dot; expires="2015-01-15 07:48:41Z"; version=0
        # Set-Cookie3: NID="67=JI_uEwUm5GDrQ_vCwAp2z_YGU7MdLm5CLMa4CNLF7RQuTDMzrrk1EjRddGcnpoFbht81LaV9spxZQQInf0mPS6lDrvcRqBBL5NOTmy8SwOzA6HWC3iTIo4-o3fO1Udkv"; path="/"; domain=".google.com.hk"; path_spec; domain_dot; expires="2013-07-17 07:48:41Z"; HttpOnly=None; version=0
        # Set-Cookie3: PREF="ID=8f7e4efca89bdb1b:U=f85a4afa4db021aa:FF=2:LD=zh-CN:NW=1:TM=1358236121:LM=1358236121:S=2WR59hDWutdnUJtF"; path="/"; domain=".google.com.hk"; path_spec; domain_dot; expires="2015-01-15 07:48:41Z"; version=0

        print "3. Demo how to auto handle cookie in file, Mozilla Format";
        cookieFilenameMozilla = "localCookiesMozilla.txt";
        cookieJarFileMozilla = cookielib.MozillaCookieJar(cookieFilenameMozilla);
        #will create (and save to) new cookie file
        cookieJarFileMozilla.save();
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJarFileMozilla));
        urllib2.install_opener(opener);
        #!!! following urllib2 will auto handle cookies
        demoUrl = "http://www.google.com/";
        response = urllib2.urlopen(demoUrl);
        #update cookies, save cookies into file
        cookieJarFileMozilla.save();
        #for demo, print cookies in file
        print "Mozilla cookies:";
        print open(cookieFilenameMozilla).read(os.path.getsize(cookieFilenameMozilla));
        # # Netscape HTTP Cookie File
        # # http://www.netscape.com/newsref/std/cookie_spec.html
        # # This is a generated file!  Do not edit.

        # .google.com   TRUE    /   FALSE   1421308121  PREF    ID=0e05040dd979207c:FF=0:NW=1:TM=1358236121:LM=1358236121:S=jcFid2XgXMIhPUPl
        # .google.com.hk    TRUE    /   FALSE   1374047321  NID 67=klMI_Z5ZPWDjUYrWSUHIE_kYI77_ziJaL0kWRoUGThagME86LKY7H-MNa2wAMI_GklIwYcD8t82qPinxzLd4GLDbmWT0OVLCXhRj0wQDC57dTNAsTs4lhVR7Yjvj2tfn
        # .google.com.hk    TRUE    /   FALSE   1421308121  PREF    ID=028f8b736db06a9a:U=6ba6d080847c8de6:FF=2:LD=zh-CN:NW=1:TM=1358236121:LM=1358236121:S=_1BcC5v3G0ZojVz8

        print "4. read cookies from file";
        parseAndSavedCookieFile = "parsedAndSavedCookies.txt"
        parsedCookieJarFile = cookielib.MozillaCookieJar(parseAndSavedCookieFile);
        #parsedCookieJarFile = cookielib.MozillaCookieJar(cookieFilenameMozilla);
        print parsedCookieJarFile; #
        parsedCookieJarFile.load(cookieFilenameMozilla);
        print parsedCookieJarFile; #, , ]>


    if __name__=="__main__":
        pythonAutoHandleCookie();

I have write sample code to demo:

  • auto handle cookies: cookie in memory
  • auto handle cookies: cookie in file
    • support two format:
      • LWP
      • Mozilla
    • two kind of operation
      • save into file
      • load from file

code:



    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    """
    Function:   【整理】Python中Cookie的处理:自动处理Cookie,保存为Cookie文件,从文件载入Cookie
                http://www.crifan.com/python_auto_handle_cookie_and_save_to_from_cookie_file

    Version:    2013-01-15
    Author:     Crifan
    Contact:    admin (at) crifan.com
    """

    import os;
    import cookielib;
    import urllib2;

    def pythonAutoHandleCookie():
        """
            Demo how to auto handle cookie in Python
                cookies in memory
                cookies in file:
                    save cookie to file
                        LWP     format
                        Mozilla format
                    load cookie from file
        """

        print "1. Demo how to auto handle cookie (in memory)";
        cookieJarInMemory = cookielib.CookieJar();
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJarInMemory));
        urllib2.install_opener(opener);
        print "after init, cookieJarInMemory=",cookieJarInMemory; #after init, cookieJarInMemory= 
        #!!! following urllib2 will auto handle cookies
        demoUrl = "http://www.google.com/";
        response = urllib2.urlopen(demoUrl);
        #here, we already got response cookies
        print "after urllib2.urlopen, cookieJarInMemory=",cookieJarInMemory;
        #after urllib2.urlopen, cookieJarInMemory= , , ]>


        print "2. Demo how to auto handle cookie in file, LWP format";
        cookieFilenameLWP = "localCookiesLWP.txt";
        cookieJarFileLWP = cookielib.LWPCookieJar(cookieFilenameLWP);
        #will create (and save to) new cookie file
        cookieJarFileLWP.save();
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJarFileLWP));
        urllib2.install_opener(opener);
        #!!! following urllib2 will auto handle cookies
        demoUrl = "http://www.google.com/";
        response = urllib2.urlopen(demoUrl);
        #update cookies, save cookies into file
        cookieJarFileLWP.save();
        #for demo, print cookies in file
        print "LWP cookies:";
        print open(cookieFilenameLWP).read(os.path.getsize(cookieFilenameLWP));
        # #LWP-Cookies-2.0
        # Set-Cookie3: PREF="ID=34c1415b570a93ae:FF=0:NW=1:TM=1358236121:LM=1358236121:S=gEVVojW4x37ht5n-"; path="/"; domain=".google.com"; path_spec; domain_dot; expires="2015-01-15 07:48:41Z"; version=0
        # Set-Cookie3: NID="67=JI_uEwUm5GDrQ_vCwAp2z_YGU7MdLm5CLMa4CNLF7RQuTDMzrrk1EjRddGcnpoFbht81LaV9spxZQQInf0mPS6lDrvcRqBBL5NOTmy8SwOzA6HWC3iTIo4-o3fO1Udkv"; path="/"; domain=".google.com.hk"; path_spec; domain_dot; expires="2013-07-17 07:48:41Z"; HttpOnly=None; version=0
        # Set-Cookie3: PREF="ID=8f7e4efca89bdb1b:U=f85a4afa4db021aa:FF=2:LD=zh-CN:NW=1:TM=1358236121:LM=1358236121:S=2WR59hDWutdnUJtF"; path="/"; domain=".google.com.hk"; path_spec; domain_dot; expires="2015-01-15 07:48:41Z"; version=0

        print "3. Demo how to auto handle cookie in file, Mozilla Format";
        cookieFilenameMozilla = "localCookiesMozilla.txt";
        cookieJarFileMozilla = cookielib.MozillaCookieJar(cookieFilenameMozilla);
        #will create (and save to) new cookie file
        cookieJarFileMozilla.save();
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJarFileMozilla));
        urllib2.install_opener(opener);
        #!!! following urllib2 will auto handle cookies
        demoUrl = "http://www.google.com/";
        response = urllib2.urlopen(demoUrl);
        #update cookies, save cookies into file
        cookieJarFileMozilla.save();
        #for demo, print cookies in file
        print "Mozilla cookies:";
        print open(cookieFilenameMozilla).read(os.path.getsize(cookieFilenameMozilla));
        # # Netscape HTTP Cookie File
        # # http://www.netscape.com/newsref/std/cookie_spec.html
        # # This is a generated file!  Do not edit.

        # .google.com   TRUE    /   FALSE   1421308121  PREF    ID=0e05040dd979207c:FF=0:NW=1:TM=1358236121:LM=1358236121:S=jcFid2XgXMIhPUPl
        # .google.com.hk    TRUE    /   FALSE   1374047321  NID 67=klMI_Z5ZPWDjUYrWSUHIE_kYI77_ziJaL0kWRoUGThagME86LKY7H-MNa2wAMI_GklIwYcD8t82qPinxzLd4GLDbmWT0OVLCXhRj0wQDC57dTNAsTs4lhVR7Yjvj2tfn
        # .google.com.hk    TRUE    /   FALSE   1421308121  PREF    ID=028f8b736db06a9a:U=6ba6d080847c8de6:FF=2:LD=zh-CN:NW=1:TM=1358236121:LM=1358236121:S=_1BcC5v3G0ZojVz8

        print "4. read cookies from file";
        parseAndSavedCookieFile = "parsedAndSavedCookies.txt"
        parsedCookieJarFile = cookielib.MozillaCookieJar(parseAndSavedCookieFile);
        #parsedCookieJarFile = cookielib.MozillaCookieJar(cookieFilenameMozilla);
        print parsedCookieJarFile; #
        parsedCookieJarFile.load(cookieFilenameMozilla);
        print parsedCookieJarFile; #, , ]>


    if __name__=="__main__":
        pythonAutoHandleCookie();

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文