很多网站使用cookie在本地硬盘中存储各种信息。可能想要查看cookie中保存的信息,或者使用cookie自动登录网站。
我们要记下表单中几个字段的ID,然后决定提交哪些虚拟值。我们首先要访问登录页面,再访问首页,查看在cookie中保存了什么。
import cookielib
import urllib
import urllib2
ID_USERNAME = 'id_username'
ID_PASSWORD = 'id_password'
USERNAME = 'you@email.com'
PASSWORD = 'mypassword'
LOGIN_URL = 'https://bitbucket.org/account/signin/?next=/'
NORMAL_URL = 'https://bitbucket.org/'
def extract_cookie_info():
# setup cookie jar
cj = cookielib.CookieJar()
login_data = urllib.urlencode({ ID_USERNAME : USERNAME, ID_PASSWORD : PASSWORD})
# create url opener
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
resp = opener.open(LOGIN_URL, login_data)
# send login info
for cookie in cj:
print("----First time cookie: {} --> {}".format(cookie.name, cookie.value))
print("Headers: {}".format(resp.headers))
# now access without any login info
resp = opener.open(NORMAL_URL)
for cookie in cj:
print("++++Second time cookie: {} --> {}".format(cookie.name, cookie.value))
print("Headers: {}".format(resp.headers))
if __name__ == '__main__':
extract_cookie_info()