John Dorian
John Dorian

Reputation: 33

Python using urllib to authenticate to a webpage

I have read the other posts on this, but my situation is a bit unique I think. I am trying to use python to read my grades off of the school's home access center website, but I think there is something peculiar in the way they have it programmed, here is the code that I am using:

import urllib

def WebLogin(password):
    params = urllib.urlencode(
        {'txtLogin': username,
         'txtPassword': password })
    f = urllib.urlopen("http://home.tamdistrict.org/homeaccess/Student/Assignments.aspx", params)
    if "The following errors occurred while attempting to log in:" in f.read():
        print "Login failed."
        print f.read()
    else:
        print "Correct!"
        print f.read()

It always prints "Correct" no matter what I enter for the username and password. Each f.read() returns only a blank line. I am really stuck here, thanks for all of your help!

Upvotes: 1

Views: 251

Answers (1)

Ismail Badawi
Ismail Badawi

Reputation: 37177

urlopen returns a file-like object. In particular, you can only call read() once (with no arguments -- you can read in chunks by passing a size to read, but ya) -- subsequent calls to read() will return None because you've exhausted it (and unlike regular file objects, there is no seek method). You should store the result in a variable.

content = f.read()
if "The following errors occurred while attempting to log in:" in content:
    print "Login failed."
    print content
else:
    print "Correct!"
    print content

Upvotes: 3

Related Questions