2013-10-17 65 views
1

我想登錄到Moodle網站,但它返回「你還沒有登錄」頁面,這意味着認證不成功。我究竟做錯了什麼?我忘了設置參數嗎?請不要推薦機械化。我想了解它是如何在沒有圖書館的情況下運作的。我的代碼:Python:用urllib2登錄Moodle

import cookielib, urllib, urllib2, getpass 

# not the actual site, but still a Moodle example 
theurl = 'https://moodle.pucrs.br/login/index.php' 

username= raw_input("\tusername: ") 
password= getpass.getpass("\tpassword: ") 

passman = urllib2.HTTPPasswordMgrWithDefaultRealm() 

passman.add_password(None, theurl, username, password) 

cj = cookielib.CookieJar() 
opener = urllib2.build_opener(
    urllib2.HTTPRedirectHandler(), 
    urllib2.HTTPBasicAuthHandler(passman), 
    urllib2.HTTPHandler(debuglevel=0), 
    urllib2.HTTPSHandler(debuglevel=0), 
    urllib2.HTTPCookieProcessor(cj), 
) 

urllib2.install_opener(opener) 


# set headers 
opener.addheaders = [ 
    ('User-agent', ('Mozilla/4.0 (compatible; MSIE 6.0; ' 
        'Windows NT 5.2; .NET CLR 1.1.4322)')) 
] 

try: 
    #req = opener.open(theurl, data) 
    req = opener.open(theurl) 
except IOError, e: 
    print "It looks like the username or password is wrong." 

# == test == 

# visit "my courses": 
req = opener.open("https://moodle.pucrs.br/my/‎") 
content = ''.join(req.readlines()) 
print(content) 

回答

1

這是我如何登錄到網站與urllib的:

self.cookieJar = cookielib.LWPCookieJar() 
self.opener = urllib2.build_opener(


    urllib2.HTTPCookieProcessor(self.cookieJar), 
    urllib2.HTTPRedirectHandler(), 
    urllib2.HTTPHandler(debuglevel=0)) 

self.opener.addheaders = [('User-agent', "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36")] 


forms = {"username": #username here , 
     "password": #password here 
     } 

data = urllib.urlencode(forms) 
req = urllib2.Request('http://moodle.pucrs.br/login/index.php',data) 
res = self.opener.open(req) 
self.login_html = res.read() 

如果您在登錄頁面的HTML看的兩種形式的名稱是passwordusername然後你想發送請求,然後使用您製作的開瓶器打開該請求

測試一下,並告訴我它是否可用!

+0

它的工作!謝謝。我注意到我添加的一些東西,比如HTTPSHandler(),是不必要的。我將不得不查看CookieJar()和LWPCookieJar()之間的區別。 – user1755025

+0

是的,我只是使用這個相同的登錄大多數網站,所以我保留了一些不必要的東西。很高興我能幫上忙! :) – Serial