接口自動化,sso單點登陸不支持通過接口返回token,其他請求又需要token。解決方式,使用UI自動化的selenium框架登陸獲取token


找解決方案,找了好久,終於找到了, 其他博客給了我思路

F12后切換到Application,然后看token是存儲在localStorage還是sessionStorage

 

 

 

 

 

實現代碼:

LoginUrl,usename,password我都自己封裝在cfg.py文件中了
import time
from selenium import  webdriver
from cfg import LoginUrl,usename,password
class GetToken():
    def __init__(self):
        self.driver=webdriver.Chrome()
    def loginUI(self):
        self.driver.get(LoginUrl)
        self.driver.maximize_window()
        self.driver.implicitly_wait(10)
        # 登錄輸入用戶名,密碼
        self.driver.find_element_by_id('LoginForm_username').send_keys(usename)
        self.driver.find_element_by_id('LoginForm_password').send_keys(password)
        self.driver.find_element_by_id('loginSubmit').click()
        # 強制等待5秒,待session和token都成功返回並存到瀏覽器中
        time.sleep(5)

    # 獲取token
    def get_token(self):
        # 是要從localStorage中獲取還是要從sessionStorage中獲取,具體看目標系統存到哪個中
        # window.sessionStorage和直接寫sessionStorage是等效的
        # 一定要使用return,不然獲取到的一直是None
        # get的Item不一定就叫token,得具體看目標系統把token存到哪個變量中
        token = self.driver.execute_script('return localStorage.getItem("token");')
        # print('token:',token)
        return token

    #關閉瀏覽器
    def close_browser(self):
        self.driver.quit()

if __name__ == '__main__':
    gt = GetToken()
    gt.loginUI()
    ret_token=gt.get_token()
    print('獲取到的token:',ret_token)
    gt.close_browser()

結果如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM