使用python实现定时发微博

新浪微博在登录时,对用户名、密码进行了加密处理,加密算法(b64encode、rsa等等)。

登陆流程

1,根据用户名username得到加密后的用户名su

2,根据su得到一个json串,里边包含加密密码用到的各种参数,servertime、nonce等

3,根据json串和密码得到加密后的密码,然后就可以登陆了。

发送流程

新浪微博发微博的接口是:

http://www.weibo.com/aj/mblog/add?ajwvr=6&__rnd=时间戳

时间戳使用int(time.time() * 1000即可设置。

Post提交数据:

{“location”: “v6_content_home”, “appkey”: “”, “style_type”: “1”, “pic_id”:””, “text”: 微博内容, “pdetail”: “”, “rank”: “0”, “rankid”: “”, “module” :”stissue”, “pub_type”: “dialog”,”_t”: “0”}

提交数据时需要设置Headers:

self.http.headers[“Referer”] = “http://www.weibo.com/u/%s/home?wvr=5” % str(self.uid)

uid在登录时会返回。

测试结果

使用python实现定时发微博

使用python实现定时发微博

测试源码

#!/usr/bin/python

# -*- coding: utf-8 -*-

import re

import rsa

import time

import json

import base64

import logging

import binascii

import requests

import urllib.parse

class WeiBoLogin(object):

    “””

    class of WeiBoLogin, to login weibo.com

    “””

    def __init__(self):

        “””

        constructor

        “””

        self.user_name = None

        self.pass_word = None

        self.user_uniqueid = None

        self.user_nick = None

        self.Referer = None

        self.session = requests.Session()

        self.session.headers.update({“User-Agent”: “Mozilla/5.0 (Windows NT 6.3; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0”})

        self.session.get(“http://weibo.com/login.php”)

        return

    def login(self, user_name, pass_word):

        “””

        login weibo.com, return True or False

        “””

        self.user_name = user_name

        self.pass_word = pass_word

        self.user_uniqueid = None

        self.user_nick = None

        # get json data

        s_user_name = self.get_username()

        print( s_user_name= ,s_user_name)

        json_data = self.get_json_data(su_value=s_user_name)

        print( json_data= ,json_data)

        if not json_data:

            return False

        s_pass_word = self.get_password(json_data[“servertime”], json_data[“nonce”], json_data[“pubkey”])

        print( s_pass_word= ,s_pass_word)

        # make post_data

        post_data = {

            “entry”: “weibo”,

            “gateway”: “1”,

            “from”: “”,

            “savestate”: “7”,

            “userticket”: “1”,

            “vsnf”: “1”,

            “service”: “miniblog”,

            “encoding”: “UTF-8”,

            “pwencode”: “rsa2”,

            “sr”: “1280*800”,

            “prelt”: “529”,

            “url”: “http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack”,

            “rsakv”: json_data[“rsakv”],

            “servertime”: json_data[“servertime”],

            “nonce”: json_data[“nonce”],

            “su”: s_user_name,

            “sp”: s_pass_word,

            “returntype”: “TEXT”,

        }

        print( post_data= ,post_data)

        # get captcha code

        if json_data[“showpin”] == 1:

            url = “http://login.sina.com.cn/cgi/pin.php?r=%d&s=0&p=%s” % (int(time.time()), json_data[“pcid”])

            with open(“captcha.jpeg”, “wb”) as file_out:

                file_out.write(self.session.get(url).content)

            code = input(“请输入验证码:”)

            post_data[“pcid”] = json_data[“pcid”]

            post_data[“door”] = code

        print( post_data= ,post_data)

        # login weibo.com

        login_url_1 = “http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.18)&_=%d” % int(time.time())

        json_data_1 = self.session.post(login_url_1, data=post_data).json()

        if json_data_1[“retcode”] == “0”:

            params = {

                “callback”: “sinaSSOController.callbackLoginStatus”,

                “client”: “ssologin.js(v1.4.18)”,

                “ticket”: json_data_1[“ticket”],

                “ssosavestate”: int(time.time()),

                “_”: int(time.time()*1000),

            }

            response = self.session.get(“https://passport.weibo.com/wbsso/login”, params=params)

            json_data_2 = json.loads(re.search(r”((?P<result>.*))”, response.text).group(“result”))

            if json_data_2[“result”] is True:

                self.user_uniqueid = json_data_2[“userinfo”][“uniqueid”]

                self.user_nick = json_data_2[“userinfo”][“displayname”]

                logging.warning(“WeiBoLogin succeed: %s”, json_data_2)

            else:

                logging.warning(“WeiBoLogin failed: %s”, json_data_2)

        else:

            logging.warning(“WeiBoLogin failed: %s”, json_data_1)

        return True if self.user_uniqueid and self.user_nick else False

    def get_username(self):

        “””

        get legal username

        “””

        username_quote = urllib.parse.quote_plus(self.user_name)

        username_base64 = base64.b64encode(username_quote.encode(“utf-8”))

        return username_base64.decode(“utf-8”)

    def get_json_data(self, su_value):

        “””

        get the value of “servertime”, “nonce”, “pubkey”, “rsakv” and “showpin”, etc

        “””

        params = {

            “entry”: “weibo”,

            “callback”: “sinaSSOController.preloginCallBack”,

            “rsakt”: “mod”,

            “checkpin”: “1”,

            “client”: “ssologin.js(v1.4.18)”,

            “su”: su_value,

            “_”: int(time.time()*1000),

        }

        try:

            response = self.session.get(“http://login.sina.com.cn/sso/prelogin.php”, params=params)

            json_data = json.loads(re.search(r”((?P<data>.*))”, response.text).group(“data”))

        except Exception as excep:

            json_data = {}

            logging.error(“WeiBoLogin get_json_data error: %s”, excep)

        logging.debug(“WeiBoLogin get_json_data: %s”, json_data)

        return json_data

    def get_password(self, servertime, nonce, pubkey):

        “””

        get legal password

        “””

        string = (str(servertime) + ” ” + str(nonce) + ”
” + str(self.pass_word)).encode(“utf-8”)

        public_key = rsa.PublicKey(int(pubkey, 16), int(“10001”, 16))

        password = rsa.encrypt(string, public_key)

        password = binascii.b2a_hex(password)

        return password.decode()

    def get_send_data(self, pids= ):

        data = {

            “location”: “v6_content_home”,

            “appkey”: “”,

            “style_type”: “1”,

            “pic_id”: pids,

            #”text”: text,

            “text”: 测试定时发送于: +time.strftime( %Y-%m-%d %H:%M:%S ),

            “pdetail”: “”,

            “rank”: “0”,

            “rankid”: “”,

            “module”: “stissue”,

            “pub_type”: “dialog”,

            “_t”: “0”,

        }

        return data

    def send_weibo(self):

        data = self.get_send_data()

        self.Referer = “http://www.weibo.com/u/%s/home?wvr=5” % self.user_uniqueid

        self.session.headers[“Referer”] = self.Referer

        try:

            self.session.post(“https://www.weibo.com/aj/mblog/add?ajwvr=6&__rnd=%d”

                              % int(time.time() * 1000),

                              data=data)

            logging.debug( 微博[%s]发送成功 % str(weibo))

        except Exception as e:

            logging.debug(e)

            logging.debug( 微博[%s]发送失败 % str(weibo))

if __name__ == “__main__”:

    logging.basicConfig(level=logging.DEBUG, format=”%(asctime)s %(levelname)s %(message)s”)

    weibo = WeiBoLogin()

    weibo.login(“user”, “passwd”)

    while True:

        weibo.send_weibo()

        time.sleep(10)

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容