使用机械化的Python自动登录 [英] Python autologin using mechanize

查看:154
本文介绍了使用机械化的Python自动登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已修复!已更新为工作代码

FIXED! updated with working code

我一直在努力使这种自动登录的东西对我有用. 请注意,目前我仍然是Python新手.

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.

以下是我检查相关表格时发现的html代码:

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> 

我首先获取门户网站html内容,以找到正确的"pwdXXXX"变量.与每次刷新一样,密码表单的ID也会更改.据我了解,正则表达式有效.

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.

尝试传递密码时确实出错.哪让我觉得我对它的键的形式有误?我完全不知道.我也尝试使用urllib2方法而不是使用机械化.也没有结果.

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.

工作代码:

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()

推荐答案

部分问题很可能是因为关闭套接字后,您在机械化会话中使用urllib读取页面时会出现不同的 ID,因此需要一个令牌.

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.

在会话期间,您将需要保持单个连接打开.因此,我认为您需要解析对br.read()的答复的内容,才能找到pwID的值.

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.

我遗漏了urllib部分,它现在正在工作.我虽然使用str(br.form)而不是br.read().

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

这篇关于使用机械化的Python自动登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆