模拟人人登陆
#encoding=utf-8
import urllib2
import urllib
import cookielib
def renrenBrower(url,user,password):
#登陆页面,能够通过抓包工具分析获得,如fiddler。wireshark
login_page = "http://www.renren.com/PLogin.do"
try:
#获得一个cookieJar实例
cj = cookielib.CookieJar()
#cookieJar作为參数,获得一个opener的实例
opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
#伪装成一个正常的浏览器,避免有些webserver拒绝訪问。
opener.addheaders = [('User-agent','Mozilla/5.0 (Windows NT 6.3; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0')] #生成Post数据。含有登陆username密码。
data = urllib.urlencode({"email":user,"password":password}) #以post的方法訪问登陆页面,訪问之后cookieJar会自定保存cookie opener.open(login_page,data) #以带cookie的方式訪问页面 op=opener.open(url) #读取页面源代码 data= op.read() return data except Exception,e: print "aaaa" #訪问某用户的个人主页,事实上这已经实现了人人网的签到功能。http://blog.chinaunix.net/uid-25979788-id-3481639.html print renrenBrower("http://www.renren.com/home","1574038203@qq.com","123456")
分析下:
http://www.renren.com/PLogin.do
那么我们是怎么知道表单提交地址呢?
1:查看站点代码
2:查看表单
提前表单的须要的数据
如:
import urllib
import urllib2
import cookielib
filename = 'cookie1.txt'
#声明一个MozillaCookieJar对象实例来保存cookie。之后写入文件
cookie = cookielib.MozillaCookieJar(filename)
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
opener.addheaders = [('User-agent','Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)')]
postdata = urllib.urlencode({
"username":"xxxxxxxx,
"password":"xxxxxxxx",
"lt":"LT-381024-pHXsjYjSgZ2aR9P4QrG9YQ6rneqlhg",
"execution" : "e20s1",
"_eventId" : "submit"
})
#登录的URL
loginUrl = 'https://passport.youkuaiyun.com/account/login
'
#模拟登录。并把cookie保存到变量
result = opener.open(loginUrl,postdata)
#保存cookie到cookie.txt中
cookie.save(ignore_discard=True, ignore_expires=True)
#利用cookie请求訪问还有一个网址
gradeUrl = 'http://write.blog.youkuaiyun.com/postlist
'
#请求訪问查询网址
result = opener.open(gradeUrl)
print result.read()