首先,我会说我一段时间没有以这种方式登录,因此我可能会错过一些更“被接受”的方式来进行登录。
我不确定这是否是您要追求的,但是如果没有像这样的库
mechanize或更强大的框架
selenium,那么在基本情况下,您只需查看表单本身并查找即可
inputs。例如,查看
www.reddit.com,然后查看渲染页面的源,您将找到此表单:
<form method="post" action="https://ssl.reddit.com/post/login" id="login_login-main" > <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 ></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 href="/password">reset password</a> </div> <div > <button type="submit" tabindex="1">login</button> </div> <div ></div></form>
在这里,我们看到了几个
input的- ,,和。另外,请注意参数-
即表单将发布到的URL,因此将成为我们的目标。因此,现在的最后一步是将参数打包到有效负载中,并将其作为请求发送到URL。同样在下面,我们创建了一个new
,添加了处理cookie和添加标头的功能,从而为我们提供了一个更强大的打开器来执行请求):
op``user``passwd``rem``action``POST``action``opener
import cookielibimport urllibimport urllib2# Store the cookies and create an opener that will hold themcj = cookielib.cookieJar()opener = urllib2.build_opener(urllib2.HTTPcookieProcessor(cj))# Add our headersopener.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 formauthentication_url = 'https://ssl.reddit.com/post/login'# Input parameters we are going to sendpayload = { 'op': 'login-main', 'user': '<username>', 'passwd': '<password>' }# Use urllib to enpre the payloaddata = urllib.urlenpre(payload)# Build our Request object (supplying 'data' makes it a POST)req = urllib2.Request(authentication_url, data)# Make the request and read the responseresp = urllib2.urlopen(req)contents = resp.read()请注意,这会变得更加复杂-
例如,您也可以使用GMail进行此操作,但是您需要提取每次都会更改的
GALX参数(例如参数)。同样,不确定这是否是您想要的,但希望能有所帮助。



