我会先说这个,说我没有以这种方式登录一段时间,所以我可能会错过一些更多的“接受”的方法来做到这一点。
我不知道这是否是你的后来,但没有像机械化或更强大的框架像硒,在基本情况下,你只是看看表单本身和寻找输入的库。例如,查看www.reddit.com,然后查看渲染页面的源代码,您将找到以下表单:
class="login-form login-form-side">
remember me
login
这里我们看到一些输入的op,user,passwd和rem。此外,请注意action参数 – 即表单将被发布到的URL,因此将是我们的目标。所以现在最后一步是将参数打包到有效负载中,并将其作为POST请求发送到操作URL。在下面,我们创建一个新的开启者,添加处理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': '',
'passwd': ''
}
# 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参数)。再次,不知道这是否是你想要的,但希望它有帮助。