Python autologin using mechanize

。_饼干妹妹 提交于 2020-01-06 08:15:44

问题


FIXED! updated with working code

I have been going about trying to make this auto login thing working for me. Do note I'm still a Python novice at this point.

The following is the html code I found when I inspected the relevant form:

<form action="/cgi-bin/netlogin.pl" method="post" name="netlogin">
    <tr>
      <td><div align="right">Intranet userid:</div></td>
      <td><input type="text" size="20" maxlength="50" name="uid" id="uid" class="formField" /></td>
    </tr>
    <tr>
      <td><div align="right">Wachtwoord:</div></td>
      <td><input type="password" size="20" maxlength="50" name="pwd29296" class="formField" autocomplete="off"/></td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td><input type="submit" name="submit" value="Login" /></td>
    </tr>
</form> 

I start off with getting the portal html content to find the right "pwdXXXX" variable. As with every refresh, the ID for the password form changes. To my understanding this, and the regex works.

It does go wrong when trying to pass the password. Which makes me think I got it wrong with the form its keys? I have absolutely no clue. I also tried using the urllib2 approach instead of using mechanize. No result either.

Working code:

url = "https://netlogin.kuleuven.be/cgi-bin/wayf2.pl?inst=kuleuven&lang=nl&submit=Ga+verder+%2F+Continue"

br = mechanize.Browser()
br.set_handle_robots(False)
br.open(url)
br.select_form(name = "netlogin")
form = str(br.form)

uID = "uid"
dynamic_pwID = re.findall(r"(pwd\d+)", form) #pwID changes when page is refreshed
pwID = dynamic_pwID[0]

br[uID] = "xxxx"
br[pwID]= "xxxx"

res = br.submit()

回答1:


A part of your problem may well be that since you close the socket that you read the page with urllib with your mechanize session will have a different ID and so require a new token.

You will need to keep a single connection open for the duration of the session. So I think that you will need to parse the contents of the reply to br.read() to find your value for pwID.

Comment From OP:

I left out the urllib part and it's working now. I used str(br.form) instead of br.read() though.



来源:https://stackoverflow.com/questions/21686236/python-autologin-using-mechanize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!