python 2.7.5
urllib2.Request(url[, data][, headers][, origin_req_host][, unverifiable])的方法有add_data(data),get_method(),has_data(),get_data(),add_header(key, val),add_unredirected_header
Request对象介绍:
该类是URL的一个抽象类
url应为一个合法的链接
data应为发送给服务器的参数,当前只有http请求能使用data参数。当Request提供了data参数后,http请求将由get方法变为post方法。data的格式为application/x-www-form-urlencoded。可以使用urllib.urlencode()函数将2元序列转换成application/x-www-form-urlencode格式
urllib2.Request(url[, data][, headers][, origin_req_host][, unverifiable])的方法有add_data(data),get_method(),has_data(),get_data(),add_header(key, val),add_unredirected_header
Request对象介绍:
该类是URL的一个抽象类
url应为一个合法的链接
data应为发送给服务器的参数,当前只有http请求能使用data参数。当Request提供了data参数后,http请求将由get方法变为post方法。data的格式为application/x-www-form-urlencoded。可以使用urllib.urlencode()函数将2元序列转换成application/x-www-form-urlencode格式
示例:
postdata=urllib.urlencode({'username':username,
'password':passwd,
'continueURI':'http://www.verycd.com/',
'fk':fk,
'login_submit':'登录',
})
origin_req_host,unverifiable是与处理cookie利益相关,暂不理解,也尚未使用
Request对象常用方法简要介绍
add_data(data),将需要请求的数据发送至data参数,该数据将被HTTP handlers处理,该方法会使请求由get方法变为post方法
get_method(),获取http请求的请求方法(即返回get或是post)
add_header(key,val),添加文件头到请求中,不同的文件头名称不能相同,最新的添加将会覆盖以前的文件头
人人签到机器人
import urllib
import urllib2
import cookielib
def renren(url,email,password):
login_path='http://www.renren.com/PLogin.do';
try:
cookie=cookielib.CookieJar();#获取一个cookiejar实例
opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie));#获取一个HTTPCookieProcessor Handler对象
#opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie));
urllib2.install_opener(opener);#设置opener作为默认的全局handler
opener.addheaders=[('User-agent','Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31')];
postdata=urllib.urlencode({'email':email,'password':password});
#opener.open(login_path,postdata);
#op=opener.open(url);
#data=op.read();
req=urllib2.Request(login_path,postdata);
data=urllib2.urlopen(req).read();
return data
except Exception,e:
print str(e)
#访问某用户的个人主页,其实这已经实现了人人网的签到功能。
user='youremail'
password='yourpassword'
print renren("http://www.renren.com/home",user,password)