简体   繁体   中英

mechanize Python moodle login

I am trying to automate some tasks in moodle with mechanize in Python.

My first goal is to just login but for some reason, it will not work.

I always get the login screen back as a result.

Does anyone know what the problem could be:


    import http.cookiejar as cookielib
    import mechanize

    br = mechanize.Browser()
    cookiejar = cookielib.LWPCookieJar()
    br.set_cookiejar(cookiejar)

    br.set_handle_equiv(True)
    br.set_handle_gzip(True)
    br.set_handle_redirect(True)
    br.set_handle_referer(True)
    br.set_handle_robots(False)

    br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time = 1)
    br.addheaders = [( 'User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1' )]
    br.open("url-to-login")

    br.select_form(nr=0)
    br.form.controls[1]._value = "username"
    br.form.controls[2]._value = "password"
    br.submit(id="loginbtn")

    url = br.open("url-to-course")
    returnPage = url.read()
    print(returnPage)

Use this

br.form['username'] = "myusername"
br.form['password'] = "mypassword"

instead of

br.form.controls[1]._value = "myusername"
br.form.controls[2]._value = "mypassword"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM