网上找了一些资源,python爬虫模拟登陆人人网的例子,但是应该是比较早期的版本,大多已经无法登陆。而且人人网也在做一些信息验证机制也在变化,自己做了一个小爬虫,模拟登陆后在人人网发表自己的状态。
登陆是需要的信息:
postData = {'email':username,'password':password}
发表心情是所需的信息:
statusData = {'content':msg,
'_rtk':self.rtkToken,
'channel':'renren',
'hostid':self.userid,#测试中此参数没有亦可请求成功
'requestToken':self.requestToken}
此处无论是登陆,还是心情发表操作都不需要headers信息验证。但是_rtk,channel确实必须的。
# -*-coding:utf-8-*-
import urllib2
from urllib import urlencode
import re
class Renren:
requestToken = ''
rtkToken = ''
userid = ''
__isLogin = False
newStatusUrl = 'http://shell.renren.com/{}/status'
LoginUrl = 'http://www.renren.com/PLogin.do'
# 登录
def Login(self, username, password):
postData = {'email':username,
'password':password}
postData = urlencode(postData)
cookieFile = urllib2.HTTPCookieProcessor()
self.opener = urllib2.build_opener(cookieFile)
req = urllib2.Request(self.LoginUrl, postData)
result = self.opener.open(req)
if result.geturl() == 'http://www.renren.com/home' or 'http://guide.renren.com/guide':
print "login success..."
pass
else:
return False
rawHtml = result.read()
# 获取用户id
useridPattern = re.compile(r"'id':'(\d+)'")
self.userid = useridPattern.search(rawHtml).group(1)
# 查找requestToken
requestToken = re.compile(r"get_check:'(\d+)'")
requestToken2 = re.compile(r"get_check:'(-\d+)'")
token = requestToken.search(rawHtml) if requestToken.search(rawHtml) else requestToken2.search(rawHtml)
if token is None:
raise ValueError("requestToken search failed...")
self.requestToken = token.group(1)
#获取_rtkToken,更新个人状态时需要此参数
rtkPattern = re.compile(r"get_check_x:'(\w+)'")
rtktoken = rtkPattern.search(rawHtml)
if rtktoken is None:
raise ValueError("rtk token search failed...")
self.rtkToken = rtktoken.group(1)
print self.rtkToken
self.__isLogin = True
return self.__isLogin
# 获取RequestToken
def GetRequestToken(self):
return self.requestToken
# 发布个人状态
def PostStatus(self, msg):
headers = {
"Host":"shell.renren.com",
"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0",
"Referer":"http://shell.renren.com/ajaxproxy.htm"
}
if self.__isLogin:
statusData = {'content':msg,
'_rtk':self.rtkToken,
'channel':'renren',
'hostid':self.userid,#测试中此参数没有亦可请求成功
'requestToken':self.requestToken}
postStatusData = urlencode(statusData)
self.newStatusUrl = self.newStatusUrl.format(self.userid)
# print self.newStatusUrl
updataReq = urllib2.Request(self.newStatusUrl, postStatusData, headers= headers)
# print updataReq
updataResult = self.opener.open(updataReq)
if not updataResult:
raise ValueError("update failed...")
print "status update success..."
return True
return False