❌自动批量删除微博动态消息

  • A+
所属分类:编程语言

转载:自动批量删除微博动态消息weibo.py

  1. # _*_ coding: utf-8 _*_
  2. import os
  3. import re
  4. import rsa
  5. import time
  6. import json
  7. import base64
  8. import logging
  9. import binascii
  10. import requests
  11. import urllib.parse
  12. from helper import parse_mblog_mids
  13. from config import WEIBO_USERNAME, WEIBO_PASSWORD, PAGE_ONE_URL
  14. class WeiBo(object):
  15.     """
  16.     class of WeiBo, to login weibo.com
  17.     """
  18.     def __init__(self):
  19.         """
  20.         constructor
  21.         """
  22.         self.user_name = None
  23.         self.pass_word = None
  24.         self.user_uniqueid = None
  25.         self.user_nick = None
  26.         self.session = requests.Session()
  27.         self.session.headers.update({"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36"})
  28.         self.session.get("http://weibo.com/login.php")
  29.         return
  30.     def login(self, user_name, pass_word):
  31.         """
  32.         login weibo.com, return True or False
  33.         """
  34.         self.user_name = user_name
  35.         self.pass_word = pass_word
  36.         self.user_uniqueid = None
  37.         self.user_nick = None
  38.         # get json data
  39.         s_user_name = self.get_username()
  40.         json_data = self.get_json_data(su_value=s_user_name)
  41.         if not json_data:
  42.             return False
  43.         s_pass_word = self.get_password(json_data["servertime"], json_data["nonce"], json_data["pubkey"])
  44.         # make post_data
  45.         post_data = {
  46.             "entry": "weibo",
  47.             "gateway": "1",
  48.             "from": "",
  49.             "savestate": "7",
  50.             "userticket": "1",
  51.             "vsnf": "1",
  52.             "service": "miniblog",
  53.             "encoding": "UTF-8",
  54.             "pwencode": "rsa2",
  55.             "sr": "1280*800",
  56.             "prelt": "529",
  57.             "url": "http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack",
  58.             "rsakv": json_data["rsakv"],
  59.             "servertime": json_data["servertime"],
  60.             "nonce": json_data["nonce"],
  61.             "su": s_user_name,
  62.             "sp": s_pass_word,
  63.             "returntype": "TEXT",
  64.         }
  65.         # get captcha code
  66.         if json_data["showpin"] == 1:
  67.             url = "http://login.sina.com.cn/cgi/pin.php?r=%d&s=0&p=%s" % (int(time.time()), json_data["pcid"])
  68.             with open("captcha.jpeg", "wb") as file_out:
  69.                 file_out.write(self.session.get(url).content)
  70.             code = input("请输入验证码:")
  71.             post_data["pcid"] = json_data["pcid"]
  72.             post_data["door"] = code
  73.         # login weibo.com
  74.         login_url_1 = "http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.18)&_=%d" % int(time.time())
  75.         json_data_1 = self.session.post(login_url_1, data=post_data).json()
  76.         if json_data_1["retcode"] == "0":
  77.             params = {
  78.                 "callback": "sinaSSOController.callbackLoginStatus",
  79.                 "client": "ssologin.js(v1.4.18)",
  80.                 "ticket": json_data_1["ticket"],
  81.                 "ssosavestate": int(time.time()),
  82.                 "_": int(time.time()*1000),
  83.             }
  84.             response = self.session.get("https://passport.weibo.com/wbsso/login", params=params)
  85.             json_data_2 = json.loads(re.search(r"\((?P<result>.*)\)", response.text).group("result"))
  86.             if json_data_2["result"] is True:
  87.                 self.user_uniqueid = json_data_2["userinfo"]["uniqueid"]
  88.                 self.user_nick = json_data_2["userinfo"]["displayname"]
  89.                 logging.warning("WeiBo succeed: %s", json_data_2)
  90.             else:
  91.                 logging.warning("WeiBo failed: %s", json_data_2)
  92.         else:
  93.             logging.warning("WeiBo failed: %s", json_data_1)
  94.         return True if self.user_uniqueid and self.user_nick else False
  95.     def get_username(self):
  96.         """
  97.         get legal username
  98.         """
  99.         username_quote = urllib.parse.quote_plus(self.user_name)
  100.         username_base64 = base64.b64encode(username_quote.encode("utf-8"))
  101.         return username_base64.decode("utf-8")
  102.     def get_json_data(self, su_value):
  103.         """
  104.         get the value of "servertime", "nonce", "pubkey", "rsakv" and "showpin", etc
  105.         """
  106.         params = {
  107.             "entry": "weibo",
  108.             "callback": "sinaSSOController.preloginCallBack",
  109.             "rsakt": "mod",
  110.             "checkpin": "1",
  111.             "client": "ssologin.js(v1.4.18)",
  112.             "su": su_value,
  113.             "_": int(time.time()*1000),
  114.         }
  115.         try:
  116.             response = self.session.get("http://login.sina.com.cn/sso/prelogin.php", params=params)
  117.             json_data = json.loads(re.search(r"\((?P<data>.*)\)", response.text).group("data"))
  118.         except Exception as excep:
  119.             json_data = {}
  120.             logging.error("WeiBo get_json_data error: %s", excep)
  121.         logging.debug("WeiBo get_json_data: %s", json_data)
  122.         return json_data
  123.     def get_password(self, servertime, nonce, pubkey):
  124.         """
  125.         get legal password
  126.         """
  127.         string = (str(servertime) + "\t" + str(nonce) + "\n" + str(self.pass_word)).encode("utf-8")
  128.         public_key = rsa.PublicKey(int(pubkey, 16), int("10001", 16))
  129.         password = rsa.encrypt(string, public_key)
  130.         password = binascii.b2a_hex(password)
  131.         return password.decode()
  132.     def post(self, url, data):
  133.         return self.session.post(url, data=data)
  134.     def get_mblog_mids(self):
  135.         mblog_url = 'https://m.weibo.cn/api/container/getIndex?containerid=2304135610949777_-_WEIBO_SECOND_PROFILE_WEIBO&page=1'
  136.         params = {
  137.             'containerid': '2304135610949777_-_WEIBO_SECOND_PROFILE_WEIBO',
  138.             'page_type': '01',
  139.             'page': '1',
  140.         }
  141.         response = self.session.get("https://m.weibo.cn/api/container/getIndex", params=params)
  142.         mblog_ids = parse_mblog_mids(response.json())
  143.         return mblog_ids
  144. if __name__ == "__main__":
  145.     logging.basicConfig(level=logging.INFO, format="%(asctime)s\t%(levelname)s\t%(message)s")
  146.     weibo = WeiBo()
  147.     weibo.login(WEIBO_USERNAME, WEIBO_PASSWORD)

config.py

  1. import os
  2. header = {'Host': 'm.weibo.cn',
  3.           'Connection': 'keep-alive',
  4.           'Content-Length': 30,
  5.           'Accept': 'application/json, text/plain, */*',
  6.           'MWeibo-Pwa': 1,
  7.           'X-Requested-With': 'XMLHttpRequest',
  8.           'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36',
  9.           'Origin': 'https://m.weibo.cn',
  10.           'Content-Type': 'application/x-www-form-urlencoded',
  11.         #   'Referer': ' https://m.weibo.cn/profile/5610949777',
  12.           'Accept-Encoding': 'gzip, deflate, br',
  13.           'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
  14.           'Cookie': ''
  15.           }
  16. WEIBO_USERNAME = os.environ.get('WEIBO_USERNAME')
  17. WEIBO_PASSWORD = os.environ.get('WEIBO_PASSWORD')
  18. PAGE_ONE_URL = 'https://m.weibo.cn/api/container/getIndex?containerid=2304135610949777_-_WEIBO_SECOND_PROFILE_WEIBO&page_type=03&page=1'

help.py

  1. import json
  2. def parse_mblog_mids(data_dict):
  3.     if not data_dict:
  4.         return
  5.     # print('data_dict: {0}'.format(data_dict))
  6.     cards = data_dict.get('data').get('cards')
  7.     mblog_mids = [card['mblog']['mid'] for card in cards if card['card_type'] == 9]
  8.     return mblog_mids

del.py

  1. import logging  
  2. import os  
  3. import json  
  4. import time  
  5.   
  6. from config import WEIBO_PASSWORD, WEIBO_USERNAME  
  7. from weibo import WeiBo  
  8.   
  9. weibo = WeiBo()  
  10. weibo.login(WEIBO_USERNAME, WEIBO_PASSWORD)  
  11.   
  12.   
  13. def del_mblog():  
  14.     url = 'http://weibo.com/aj/mblog/del?ajwvr=6'  
  15.     mids = weibo.get_mblog_mids()  
  16.     print('mids:{0}'.format(mids))  
  17.     for mid in mids:  
  18.         data = {'mid': mid}  
  19.         response = weibo.post(url, data=json.dumps(data))  
  20.         logging.debug('del status:', response.status_code)  
  21.         print('del status: ', response.status_code)  
  22.         print(response.content.decode('utf8'))  
  23.         time.sleep(2)  
  24.   
  25.   
  26. if __name__ == "__main__":  
  27.     logging.basicConfig(level=logging.DEBUG, format="%(asctime)s\t%(levelname)s\t%(message)s")  
  28.     del_mblog()  
weinxin
我的微信公众号
爱真理,得永生!          爱在灵灵久博客,网罗天下,福利大家!

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: