python模擬登陸新浪微博 模擬新浪微博登錄的完整請求過程

在心力憔悴的時候,絕處逢生!搞了幾天,成功了,哈哈哈啊哈哈!

import requests
import time
import json
import re
import base64
import rsa
import binascii
import execjs

# 模擬新浪微博登錄的完整請求過程,包括預(yù)登錄,重定向,和最后返回個人主頁;
# 該項目的難點再與破解js加密的post數(shù)據(jù),在此基礎(chǔ)上,還需要多次對服務(wù)器發(fā)起多個請求,
# 完整的流程走下來,微博才鞥夠成功的登錄上


# 整體的框架梳理:  全程用session保存cookie 哦
#                  第一:通過抓包可以發(fā)現(xiàn),我們在登錄微博首頁的時候,客戶端向服務(wù)器發(fā)起的請求并不是首頁的地址,而是/vistor/vistor
# 為了全真模擬,那么我們也必須先請求這個地址,然后再;
#                  第二:請求微博的首頁,似乎沒什么意思,就是要走這個流程,也許不需要,代碼還沒有優(yōu)化;
#                  第三:預(yù)登錄,這一步就很重要了,因為在后面的post登錄請求中會有很多的表單數(shù)據(jù),預(yù)登錄的響應(yīng)信息有很多我們想要的;
#                  第四:找到加密password等數(shù)據(jù)的加密js,在js中找到加密的方式,破解加密;
#                  第五:發(fā)起post登錄請求;
#                  第六:發(fā)起多次的重定向請求
#                  第七:打開個人首頁,到此便大功告成;perfect?。。。?!
class WeiBo:

    def __init__(self,name,password):
        self.start_url = 'https://passport.weibo.com/visitor/visitor'
        self.user_name = name
        self.user_password = password

    def vister(self):
        headers1 = {
            "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
        }
        data1 = {
            "entry": "miniblog",
            "a": "enter",
            "url": "https://weibo.com/",
            "domain": ".weibo.com",
            "ua": "php-sso_sdk_client-0.6.23",
            "_rand": round(time.time(), 4),
        }
        self.ss = requests.Session()
        self.r = self.ss.get(self.start_url,headers = headers1,params = data1)
        self.url = self.r.url

    def first(self):
        # 打開微博首頁;
        first_page_url = 'https://weibo.com/'
        headers2 = {
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
        "Referer": self.url,
    }
        content = self.ss.get(first_page_url,headers = headers2)

    def prelogin(self):
        # 預(yù)登陸,拿到服務(wù)器返回的加密信息;
        prelogin_url = 'https://login.sina.com.cn/sso/prelogin.php'
        params = {
            "entry": "weibo",
            "callback": "sinaSSOController.preloginCallBack",
            'su': '',
            "rsakt":"mod",
            "client": "ssologin.js(v1.4.19)",
            "_": int(time.time()*1000)
        }
        content = self.ss.get(prelogin_url,params=params)

        try:
            pattern = re.compile(r'sinaSSOController.preloginCallBack\((.+?)\)')
            content = re.findall(pattern,content.text)[0]
            js = json.loads(content)
            self.servertime = js['servertime']
            self.nonce = js['nonce']
            self.pubkey = js['pubkey']
            self.rsakv = js['rsakv']
            self.exectime = js['exectime']
            print('服務(wù)器返回的密碼提取成功!')

        except:
            print('json解析不了')

    def password(self):
        # 解密js加密后的用戶密碼;用python rsa庫加密用戶密碼(這是解密的第一種方式)
        rsakey = rsa.PublicKey(int(self.pubkey,16),int('10001',16))
        strall = str(self.servertime) + '\t' + self.nonce + '\n' + self.user_password
        content = rsa.encrypt(strall.encode('utf-8'),rsakey)
        self.sp = binascii.b2a_hex(content)
    def password2(self):
        # 解密的第二種方式,通過execjs 調(diào)用PhantomJs,直接執(zhí)行js代碼,難道函數(shù)的返回值(密碼);
        with open('totall.js','r',encoding='utf-8') as f:
            source = f.read()
        phantom = execjs.get('PhantomJs')
        phantom_compile = phantom.compile(source)
        call = phantom_compile.call('get_pass', 'nishijiba22', self.nonce, self.servertime, self.pubkey)
        return call
    def login(self):
        form_data = {
        "entry": "weibo",
        "gateway": "1",
        'from':'',
        "savestate": "7",
        "qrcode_flag": "false",
        "useticket": "1",
        "pagerefer":self.url,
        "su": base64.b64encode(self.user_name.encode('utf-8')),
        "service": "miniblog",
        "servertime": int(time.time()),
        "nonce": self.nonce,
        "pwencode": "rsa2",
        "rsakv": self.rsakv,
        "sp": self.password2(),
        "sr": "1366*768",
        "encoding": "UTF-8",
        "prelt": int(time.time()*1000)-self.exectime,
        "url":"https://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack",
        "returntype": "META"
        }
        url = 'https://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.19)'
        headers = {
            "Origin": "https://weibo.com",
            "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
            "Referer": "https://weibo.com/",
        }
        content = self.ss.post(url,headers=headers,data=form_data).content.decode('gbk')
        pattern = re.compile(r'location.replace\("(.+?)"\)')
        self.cross_url = re.findall(pattern,content)[0]
    # 別急別急你得到的還不是最終結(jié)果,新浪就是這么變態(tài)

    def home(self):
        # 獲取個人主頁的地址

        # 處理第一個重定向
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
        }
        content = self.ss.get(self.cross_url,headers=headers).content.decode('GBK')
        url2 = re.findall(r"location.replace\('(.+?)'\)",content)[0]
        self.ss.get(url2,headers=headers)
        # 處理第二個重定向;
        url = 'https://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack&sudaref=weibo.com'
        content = self.ss.get(url,headers=headers).content.decode('gbk')
        pattern = r'"uniqueid":"(\d+?)"'
        try:
            uuid = re.findall(pattern, content)[0]
        except:
            print('沒有匹配到uniquid')
        else:
            # 處理第三個重定向
            url3 = 'https://weibo.com/nguide/interest'
            self.ss.get(url3,headers=headers)
            # 處理第四個重定向
            url4= 'https://weibo.com/nguide/interests'
            self.ss.get(url4,headers=headers)
            # 拼接個人主頁
            url = 'https://weibo.com/u/{}/home'.format(uuid)
            headers = {
                "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
                "Referer": "https://weibo.com/",

            }
            home_page = self.ss.get(url,headers=headers).text
            print('出結(jié)果了哦'*9)
            print(home_page)

    def main(self):
        self.vister()
        self.first()
        self.prelogin()
        # self.password()
        self.login()
        self.home()

if __name__ == '__main__':
    name = 'your user name'
    password = 'your password'
    weibo = WeiBo(name,password)
    weibo.main()

文章寫的不夠詳細(xì),如有不懂之處,歡迎留言探討;

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容