By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,190 Members | 777 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,190 IT Pros & Developers. It's quick & easy.

Help With Cookie Jar/Urllib To Log In

P: 2
For some reason this script isn't working and I dont know what it is.
I believe the problem lies in the following lines of code since the script works with a different website and username/password combination:

resp = opener.open('http://www.amm.com/login.asp')
theurl = 'http://www.amm.com/login.asp'
body={'username':'AMMT54590570','password':'AMMT32 564288'}


Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/env python
  2. # -*- coding: UTF-8 -*-
  3.  
  4. import cookielib
  5. import urllib
  6. import urllib2
  7.  
  8. cj = cookielib.CookieJar()
  9. opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(c  j))
  10. resp = opener.open('http://www.amm.com/login.asp') # save a cookie
  11.  
  12. theurl = 'http://www.amm.com/login.asp'
  13. # an example url that sets a cookie, try different urls here and see the cookie collection you can make !
  14. body={'username':'AMMT54590570','password':'AMMT32  564288'}
  15. txdata = urllib.urlencode(body)
  16. # if we were making a POST type request, we could encode a dictionary of values here - using urllib.urlencode
  17. txheaders =  {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}
  18. # fake a user agent, some websites (like google) don't like automated exploration
  19.  
  20.  
  21. try:
  22.     req = urllib2.Request(theurl, txdata, txheaders) # create a request object
  23.     handle = opener.open(req) # and open it to return a handle on the url
  24.     HTMLSource = handle.read()
  25.     f = file('test.html', 'w')
  26.     f.write(HTMLSource)
  27.     f.close()
  28.  
  29. except IOError, e:
  30.     print 'We failed to open "%s".' % theurl
  31.     if hasattr(e, 'code'):
  32.         print 'We failed with error code - %s.' % e.code
  33.     elif hasattr(e, 'reason'):
  34.         print "The error object has the following 'reason' attribute :", e.reason
  35.         print "This usually means the server doesn't exist, is down, or we don't have an internet connection."
  36.         sys.exit()
  37.  
  38. else:
  39.     print 'Here are the headers of the page :'
  40.     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)
Oct 29 '08 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.