Problem Description
I am trying to log in to a Moodle website, but it returns the "you haven't logged in yet" page, which means authentication wasn't successful. What am I doing wrong? Am I forgetting to set a parameter? Please don't recommend *mechanize*. I want to understand how it works without a library. My code:
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)
AI-Generated Solution
Powered by LMSouq AI · GPT-4.1-mini
Analyzing problem and generating solution…
Was this solution helpful?