hellokitty111
7/1/2014 - 1:29 PM

Python 登录人人网 renren.com

Python 登录人人网 renren.com

#!/usr/bin/env python
#coding=utf-8
#Author:Richard Liu
#Blog: http://richardxxx0x.wicp.net
#Email:<richardxxx0x@gmail.com>
 
"""
.---. .---..-..-..---. .---..-..-.
| |-< | |- | .` || |-< | |- | .` |
`-'`-'`---'`-'`-'`-'`-'`---'`-'`-'
Login to renren and post messages

USAGE: python renren.py <messages>
EXAMPLE: python renren.py "你好啊"
"""

import sys
import re
import getpass
import urllib
import urllib2
import cookielib

class RenRen():
  def __init__(self):
    #cookie
    self.cj = cookielib.LWPCookieJar()
    self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
    urllib2.install_opener(self.opener)
  
  def getToken(self):
    try:
      content =  self.operate.readlines()
      matching = [s for s in content if "get_check"  in s]
      p = re.compile("get_check:'(.*)',get_check_x:'(.*)',env")
      result = p.search(''.join(matching))
      self.REQUEST_TOKEN = result.group(1)
      self._RTK = result.group(2)

      #get userid
      hostid = [s for s in content if "hostid" in s]
      p = re.compile('value="(.*)"')
      result =  p.search(''.join(hostid))
      self.userid = result.group(1)
      print 'token获取成功'
    except Exception:
      print '获取token失败'
      exit(0)


  def login(self,email,password):
    self.email = email
    self.password = password
    self.domain = 'renren.com'
    loginUrl = "http://www.renren.com/PLogin.do"
    payload = {
                       "email":self.email,
                       "password":self.password,
                       "domain":self.domain
                      }
    postdata = urllib.urlencode(payload)
    request= urllib2.Request(loginUrl,postdata)
    print "开始登录...\n"
    self.operate = self.opener.open(request)
    geturl = self.operate.geturl()
    if 'failCode' in geturl:
      print '输入的邮箱或者密码错误,请重新输入。'
      return -1
    else:
      print '登录成功'    
      return 0
    
    
    
  def post(self,poststring):
    try:
      posturl = "http://shell.renren.com/%s/status"  % (self.userid)   ##my account
      payload = {
                        "content":poststring,
                        "requestToken":self.REQUEST_TOKEN,
                        "_rtk":self._RTK,
                        "privacyParams":{"sourceControl": 99},
                        "channel":"renren"
                       }
      postdata = urllib.urlencode(payload)
      request = urllib2.Request(posturl,postdata)
      response = self.opener.open(request)
      print '发表成功'
      
    except Exception:
      print '发表失败'


if __name__ == "__main__":
  print __doc__
  if len(sys.argv) == 2:
    renren = RenRen()
    faileCode = -1
    while faileCode == -1:
      email = raw_input("请输入校内网邮箱:")
      password = getpass.getpass("请输入校内网密码:")
      faileCode = renren.login(email,password)
    print '开始获取token'
    renren.getToken()
    print '开始发表状态'
    poststring = sys.argv[1]
    renren.post(poststring)