此代码示例将允许您获取受 google 登录保护的 /secure 页面的内容。不要忘记设置电子邮件、密码和应用程序 ID。然后,您可以使用此开启器获取其他受保护的页面。
import urllib
import urllib2
import cookielib
import logging
EMAIL = ''
PASSWORD = ''
APPID = 'YOURAPPID'
# Setup to be able to get the needed cookies that GAE returns
cookiejar = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))
urllib2.install_opener(opener)
# This is the setup to construct the login URL for authentication.
authreq_data = urllib.urlencode({'Email': EMAIL,
'Passwd': PASSWORD,
'service': 'ah',
'source': '',
'accountType': 'HOSTED_OR_GOOGLE'})
# Get an AuthToken from Google Accounts
auth_req = urllib2.Request('https://www.google.com/accounts/ClientLogin',
data=authreq_data)
try:
auth_resp = opener.open(auth_req)
logging.info('Successful authorization as %s' % EMAIL)
except urllib2.HTTPError:
logging.warning('Authorization as %s failed. '
'Please, check your email and password' % EMAIL)
auth_resp_body = auth_resp.read()
auth_resp_dict = dict(x.split('=')
for x in auth_resp_body.split('\n') if x)
authtoken = auth_resp_dict['Auth']
authreq_data = urllib.urlencode({'continue': 'http://%s.appspot.com/secure' % APPID,
'auth': authtoken})
login_uri = ('http://%s.appspot.com/_ah/login?%s' % (APPID, authreq_data))
# Do the actual login and getting the cookies.
print opener.open(urllib2.Request(login_uri)).read()