一.urllib+urllib2+cookielib版
# -*- coding:utf-8 -*-
import urllib2,urllib,cookielib
data={"email":"your email","password":"your password"}
post_data=urllib.urlencode(data)#将dict转换成url参数
cj=cookielib.CookieJar()
opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
headers ={"User-agent":"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1"}
req=urllib2.Request("http://www.renren.com/PLogin.do",post_data,headers)
content=opener.open(req)
for index, cookie in enumerate(cj):#获得index和values
print index,cookie;
con=opener.open("http://www.renren.com/548056053/profile")
print con.geturl()
二.requests版
# -*- coding:utf-8 -*-
import requests
s=requests.Session()
headers ={"User-agent":"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1"}
logininfo={"email":"your email","password":"your password"}
r=s.post("http://www.renren.com/PLogin.do",data=logininfo,headers=headers)
r2=s.get("http://www.renren.com/548056053/profile")
print r2.url
相比之下request方便不少,其中的session功能就是为这种cookie保持的需求而生的,这种情况根本不需要手动显式处理cookie。