Advertisement
parkdream1

cookielib.py

Jun 7th, 2013
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.08 KB | None | 0 0
  1. #!/usr/local/bin/python
  2. # 31-08-04
  3. #v1.0.0
  4.  
  5. # cookie_example.py
  6. # An example showing the usage of cookielib (New to Python 2.4) and ClientCookie
  7.  
  8. # Copyright Michael Foord
  9. # You are free to modify, use and relicense this code.
  10. # No warranty express or implied for the accuracy, fitness to purpose or otherwise for this code....
  11. # Use at your own risk !!!
  12.  
  13. # If you have any bug reports, questions or suggestions please contact me.
  14. # If you would like to be notified of bugfixes/updates then please contact me and I'll add you to my mailing list.
  15. # E-mail michael AT foord DOT me DOT uk
  16. # Maintained at www.voidspace.org.uk/atlantibots/pythonutils.html
  17.  
  18. COOKIEFILE = 'cookies.lwp'          # the path and filename that you want to use to save your cookies in
  19. import os.path
  20.  
  21. cj = None
  22. ClientCookie = None
  23. cookielib = None
  24.  
  25. try:                                    # Let's see if cookielib is available
  26.     import cookielib            
  27. except ImportError:
  28.     pass
  29. else:
  30.     import urllib2    
  31.     urlopen = urllib2.urlopen
  32.     cj = cookielib.LWPCookieJar()       # This is a subclass of FileCookieJar that has useful load and save methods
  33.     Request = urllib2.Request
  34.  
  35. if not cookielib:                   # If importing cookielib fails let's try ClientCookie
  36.     try:                                            
  37.         import ClientCookie
  38.     except ImportError:
  39.         import urllib2
  40.         urlopen = urllib2.urlopen
  41.         Request = urllib2.Request
  42.     else:
  43.         urlopen = ClientCookie.urlopen
  44.         cj = ClientCookie.LWPCookieJar()
  45.         Request = ClientCookie.Request
  46.        
  47. ####################################################
  48. # We've now imported the relevant library - whichever library is being used urlopen is bound to the right function for retrieving URLs
  49. # Request is bound to the right function for creating Request objects
  50. # Let's load the cookies, if they exist.
  51.    
  52. if cj != None:                                  # now we have to install our CookieJar so that it is used as the default CookieProcessor in the default opener handler
  53.     if os.path.isfile(COOKIEFILE):
  54.         cj.load(COOKIEFILE)
  55.     if cookielib:
  56.         opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
  57.         urllib2.install_opener(opener)
  58.     else:
  59.         opener = ClientCookie.build_opener(ClientCookie.HTTPCookieProcessor(cj))
  60.         ClientCookie.install_opener(opener)
  61.  
  62. # If one of the cookie libraries is available, any call to urlopen will handle cookies using the CookieJar instance we've created
  63. # (Note that if we are using ClientCookie we haven't explicitly imported urllib2)
  64. # as an example :
  65.  
  66. theurl = 'http://www.diy.co.uk'         # an example url that sets a cookie, try different urls here and see the cookie collection you can make !
  67. txdata = None                                                                           # if we were making a POST type request, we could encode a dictionary of values here - using urllib.urlencode
  68. txheaders =  {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}          # fake a user agent, some websites (like google) don't like automated exploration
  69.  
  70. try:
  71.     req = Request(theurl, txdata, txheaders)            # create a request object
  72.     handle = urlopen(req)                               # and open it to return a handle on the url
  73. except IOError, e:
  74.     print 'We failed to open "%s".' % theurl
  75.     if hasattr(e, 'code'):
  76.         print 'We failed with error code - %s.' % e.code
  77. else:
  78.     print 'Here are the headers of the page :'
  79.     print handle.info()                             # handle.read() returns the page, handle.geturl() returns the true url of the page fetched (in case urlopen has followed any redirects, which it sometimes does)
  80.  
  81. print
  82. if cj == None:
  83.     print "We don't have a cookie library available - sorry."
  84.     print "I can't show you any cookies."
  85. else:
  86.     print 'These are the cookies we have received so far :'
  87.     for index, cookie in enumerate(cj):
  88.         print index, '  :  ', cookie        
  89.     cj.save(COOKIEFILE)                     # save the cookies again
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement