2011-12-24 53 views
1

我已經閱讀了關於此的其他文章,但我認爲我的情況有點獨特。我想使用Python來閱讀我的成績離開學校的家庭接入中心的網站,但我覺得有東西在他們有它編程的方式奇特,這裏是我使用的代碼:使用urllib驗證網頁的Python

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() 

無論我輸入用戶名和密碼,它總是打印「正確」。每個f.read()只返回一個空行。我真的被困在這裏,謝謝你的幫助!

回答

3

urlopen返回一個類似文件的對象。特別是,您只能撥打read()一次(沒有參數 - 您可以通過將大小傳遞給read,但是雅)來讀取 - 隨後調用read()將返回None,因爲您已經用盡它(並且不像常規文件對象,沒有seek方法)。您應該將結果存儲在一個變量中。

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