我会先说我已经有一段时间没有以这种方式登录了,所以我可能会错过一些更“被接受”的方法。
我不确定这是否是你想要的,但没有像这样的图书馆mechanize
或更强大的框架,例如selenium
,在基本情况下,您只需查看表格本身并找出inputs
。例如,查看www.reddit.com
,然后查看渲染页面的源码,你会发现这样的形式:
<form method="post" action="https://ssl.reddit.com/post/login" id="login_login-main"
class="login-form login-form-side">
<input type="hidden" name="op" value="login-main" />
<input name="user" placeholder="username" type="text" maxlength="20" tabindex="1" />
<input name="passwd" placeholder="password" type="password" tabindex="1" />
<div class="status"></div>
<div id="remember-me">
<input type="checkbox" name="rem" id="rem-login-main" tabindex="1" />
<label for="rem-login-main">remember me</label>
<a class="recover-password" href="/password">reset password</a>
</div>
<div class="submit">
<button class="btn" type="submit" tabindex="1">login</button>
</div>
<div class="clear"></div>
</form>
这里我们看到几个input
's - op
, user
, passwd
and rem
。另外,请注意action
参数 - 这是表单将发布到的 URL,因此将是我们的目标。所以现在最后一步是将参数打包到有效负载中并将其作为POST
请求给action
网址。同样在下面,我们创建了一个新的opener
,添加处理 cookie 并添加标头的功能,为我们提供了一个稍微更强大的开启器来执行请求):
import cookielib
import urllib
import urllib2
# Store the cookies and create an opener that will hold them
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
# Add our headers
opener.addheaders = [('User-agent', 'RedditTesting')]
# Install our opener (note that this changes the global opener to the one
# we just made, but you can also just call opener.open() if you want)
urllib2.install_opener(opener)
# The action/ target from the form
authentication_url = 'https://ssl.reddit.com/post/login'
# Input parameters we are going to send
payload = {
'op': 'login-main',
'user': '<username>',
'passwd': '<password>'
}
# Use urllib to encode the payload
data = urllib.urlencode(payload)
# Build our Request object (supplying 'data' makes it a POST)
req = urllib2.Request(authentication_url, data)
# Make the request and read the response
resp = urllib2.urlopen(req)
contents = resp.read()
请注意,这可能会变得更加复杂 - 例如,您也可以使用 GMail 来执行此操作,但您需要引入每次都会更改的参数(例如GALX
范围)。再次强调,不确定这是否是您想要的,但希望它有所帮助。