<p>通常您需要cookies来登录站点,这意味着cookielib、urllib和urllib2。下面是我在玩Facebook网络游戏时写的一节课:</p>
<pre><code>import cookielib
import urllib
import urllib2
# set these to whatever your fb account is
fb_username = "your@facebook.login"
fb_password = "secretpassword"
class WebGamePlayer(object):
def __init__(self, login, password):
""" Start up... """
self.login = login
self.password = password
self.cj = cookielib.CookieJar()
self.opener = urllib2.build_opener(
urllib2.HTTPRedirectHandler(),
urllib2.HTTPHandler(debuglevel=0),
urllib2.HTTPSHandler(debuglevel=0),
urllib2.HTTPCookieProcessor(self.cj)
)
self.opener.addheaders = [
('User-agent', ('Mozilla/4.0 (compatible; MSIE 6.0; '
'Windows NT 5.2; .NET CLR 1.1.4322)'))
]
# need this twice - once to set cookies, once to log in...
self.loginToFacebook()
self.loginToFacebook()
def loginToFacebook(self):
"""
Handle login. This should populate our cookie jar.
"""
login_data = urllib.urlencode({
'email' : self.login,
'pass' : self.password,
})
response = self.opener.open("https://login.facebook.com/login.php", login_data)
return ''.join(response.readlines())
</code></pre>
<p>您不一定需要HTTPS或重定向处理程序,但它们不会造成伤害,而且它使开放器更加健壮。你也可能不需要饼干,但很难仅仅从你发布的表单中分辨出来。我怀疑你可能,纯粹是从被评论掉的“记住我”输入。</p>