Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:Moodle使用urllib2登录_Python_Urllib2_Moodle - Fatal编程技术网

Python:Moodle使用urllib2登录

Python:Moodle使用urllib2登录,python,urllib2,moodle,Python,Urllib2,Moodle,我正在尝试登录Moodle网站,但它会返回“您尚未登录”页面,这意味着身份验证未成功。我做错了什么?我忘了设置参数了吗?请不要推荐机械化。我想了解没有图书馆它是如何工作的。我的代码: import cookielib, urllib, urllib2, getpass # not the actual site, but still a Moodle example theurl = 'https://moodle.pucrs.br/login/index.php' username= ra

我正在尝试登录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)

以下是我使用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,两个表单的名称是
password
username
,则您希望发送请求,然后使用所做的开场白打开该请求


测试一下,告诉我它是否有效

成功了!非常感谢。我注意到我添加的一些东西,比如HTTPSHandler(),是不必要的。我必须研究CookieJar()和LWPCookieJar()之间的区别。是的,我只是在大多数网站上使用相同的登录名,所以我保留了一些不必要的东西。很高兴我能帮忙!:)