Python - How to tell you are logged in with urllib2

When you visit the site normally, we can use urllib2.Request as such.

import urllib2, base64
req = urllib2.Request("")
base64string = base64.encodestring("%s:%s" % ("username", "password")).replace("\n", "")
req.add_header("Authorization", "Basic %s" % base64string)
requested = urllib2.urlopen(req)


But how do we know if you are logged in or not? Because you could just open the wrong authorization url.


source to share

1 answer

Maybe you should look at () to see what the page you just typed says :) Also look at () for headers sent by the server.

And you have to do it in try: ... except:

order to catch mistakes. See

FWIW, the modern approach is to use the query module.


Here's an excerpt from some code I wrote a couple of years ago.

import urllib2

def post(url, params):    
    txdata = urllib.urlencode(params)
        # create a request object
        req = urllib2.Request(url, txdata)

        # and open it to return a handle on the url
        handle = urllib2.urlopen(req)

    except IOError, e:
        print >>sys.stderr, 'We failed to open "%s".' % url
        if hasattr(e, 'code'):
            print >>sys.stderr, 'We failed with error code - %s.' % e.code
        elif hasattr(e, 'reason'):
            print >>sys.stderr, "The error object has the following 'reason' attribute :"
            print >>sys.stderr, e.reason
            print >>sys.stderr, "This usually means the server doesn't exist,"
            print >>sys.stderr, "is down, or we don't have an internet connection."
        #raise SystemExit, 1
        print >>sys.stderr, 'Here are the headers of the page :\n%s\n' %
        true_url = handle.geturl()
        print >>sys.stderr, "\nTrue URL = '%s'\n" % true_url

        return true_url


Hope this gives you some ideas.


To handle cookies, just do this before creating the request object:

    # build opener with HTTPCookieProcessor
    cookie_handler = urllib2.HTTPCookieProcessor()
    opener = urllib2.build_opener(cookie_handler)




All Articles