python 使用蟒蛇登陆微博

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 使用蟒蛇登陆微博相关的知识,希望对你有一定的参考价值。

#-------------------------------------------------------------------------------
# Name:        weibo登录模块
# Purpose:
#
# Author:      bluebird
#
# Created:     01/02/2016
# Copyright:   (c) bluebird 2016
# Licence:     <your licence>
#-------------------------------------------------------------------------------
from urllib import request
import re,json,base64

class WeiBoLogin:
    def __init__(self,uid,pwd,enableProxy=False):
        '''初始化WeiboLogin,enableProxy表示是否使用代理服务器,默认关闭'''

        print("正在初始化登录……")
        self.username=uid
        self.password=pwd
        self.enableProxy=enableProxy
        self.serverUrl= "http://login.sina.com.cn/sso/prelogin.php?entry=weibo&callback=sinaSSOController.preloginCallBack&su=&rsakt=mod&client=ssologin.js(v1.4.11)&_=1379834957683"
        self.loginUrl= "http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.11)"
        self.posthead= {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; rv:24.0) Gecko/20100101 Firefox/24.0'}


    def login(self):
        self.EnableCookie(self.enableProxy) #cookie或代理服务器配置
        serverTime, nonce, pubkey, rsakv = GetServerData()#登陆的第一步
        postData = PostEncode(self.username, self.password, serverTime, nonce, pubkey, rsakv)#加密用户和密码
        print("Post data length:%s\n" %len(postData))

        req = request.Request(self.loginUrl, postData, self.posthead)
        result = request.urlopen(req)#登陆的第二步——解析新浪微博的登录过程中3
        text = result.read()
        try:
            p = re.compile('location\.replace\([\'"](.*?)[\'"]\)')
            loginUrl = p.search(text).group(1)  #解析重定位结果
            request.urlopen(loginUrl)
        except:
            print('Login error!')
            return False

        print('Login sucess!')
        return True


    def EnableCookie(self,enableProxy):
       cookiejar=cookiejar.LWPCookieJar()
       cookie_support=request.HTTPCookieProcessor(cookie)

       if enableProxy:
            proxy_support=request.ProxyHandler({'http':'http://xxxxx.pac'})
            opener=request.build_opener(proxy_support,cookie_support,request.HTTPHandler)
            print("已经支持代理")
       else:
            opener=request.build_opener(cookie_support,request.HTTPHandler)

       request.install_opener(opener)


    def GetServerData(self):
        serverdata=request.urlopen(self.serverUrl).read()

        p = re.compile('\((.*)\)')
        jsonData = p.search(serverdata).group(1)
        data = json.loads(jsonData)
        serverTime = str(data['servertime'])
        nonce = data['nonce']
        pubkey = data['pubkey']
        rsakv = data['rsakv']
##        servertime = re.findall('"servertime":(.*?),' , preLogin)[0]
##        pubkey = re.findall('"pubkey":"(.*?)",' , preLogin)[0]
##        rsakv = re.findall('"rsakv":"(.*?)",' , preLogin)[0]
##        nonce = re.findall('"nonce":"(.*?)",' , preLogin)[0]

        return serverTime, nonce, pubkey, rsakv

    def PostEncode(userName, passWord, serverTime, nonce, pubkey, rsakv):
        "Used to generate POST data"

        encodedUserName = GetUserName(userName)#用户名使用base64加密
        encodedPassWord = get_pwd(passWord, serverTime, nonce, pubkey)#目前密码采用rsa加密
        postPara = {
            'entry': 'weibo',
            'gateway': '1',
            'from': '',
            'savestate': '7',
            'userticket': '1',
            'ssosimplelogin': '1',
            'vsnf': '1',
            'vsnval': '',
            'su': encodedUserName,
            'service': 'miniblog',
            'servertime': serverTime,
            'nonce': nonce,
            'pwencode': 'rsa2',
            'sp': encodedPassWord,
            'encoding': 'UTF-8',
            'prelt': '115',
            'rsakv': rsakv,
            'url': 'http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack',
            'returntype': 'META'
        }
        postData = urllib.parse.urlencode(postPara).encode('utf-8') #网络编码

        return postData

    def GetUserName(userName):
        "Used to encode user name"

        userNameTemp = request.quotee(userName)
        userNameEncoded = base64.encodestring(bytes(userNameTemp , encoding = 'utf-8'))
        return userNameEncoded


    def get_pwd(password, servertime, nonce, pubkey):
        rsaPublickey = int(pubkey, 16)
        key = rsa.PublicKey(rsaPublickey, 65537) #创建公钥
        message =  bytes(str(servertime) + '\t' + str(nonce) + '\n' + str(pwd) , encoding = 'utf-8') #拼接明文js加密文件中得到
        passwd = rsa.encrypt(message, key) #加密
        passwd = binascii.b2a_hex(passwd) #将加密信息转换为16进制。
        return passwd

以上是关于python 使用蟒蛇登陆微博的主要内容,如果未能解决你的问题,请参考以下文章

python 练手蟒蛇脚本,登陆页1论坛打卡签到

Python模拟登陆万能法-微博|知乎

python-微博模拟登陆

如何使用python根据关键词抓取微博

Python系列之——利用Python实现微博监控

如何用python绘制彩色蟒蛇