#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import re
import urllib
import urllib2
import cookielib
def main():
host_url = 'http://www.baidu.com/'
post_url = 'https://passport.baidu.com/v2/api/?login'
get_token_url = 'https://passport.baidu.com/v2/api/?getapi&class=login&tpl=mn&tangram=true'
username = '********'
password = '********'
cookie_jar = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie_jar))
#get cookie
opener.open(host_url)
#get token value
token_value = re.search(r'\\w{32}', opener.open(get_token_url).read()).group()
#make post data
post_data = {
'username' : username,
'password' : password,
'token' : token_value,
'tpl' : 'mn'
}
post_data = urllib.urlencode(post_data)
#build request
request = urllib2.Request(post_url, post_data)
#login
opener.open(request).read()
for cookie in cookie_jar:
print cookie
if __name__ == '__main__':
main()