python中使用selenium獲取登陸賬號的token


記錄一下工作之余需要用到內容:

  • 瀏覽器靜默模式下的自動化登陸操作
  • 獲取token

話不多說,直接代碼好了

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
#瀏覽器模式設置
chrome_options=Options()
chrome_options.add_argument('--headless')
"""最終的效果:不會彈出瀏覽器窗口""" driver
= webdriver.Chrome(chrome_options=chrome_options) url = "https://www.xxxx.com/index"

def get_token(username, password):
  #操作瀏覽器,打開url,用戶名密碼登陸 driver.
get(url) driver.find_element_by_id("userName").send_keys(username) driver.find_element_by_id("password").send_keys(password) driver.find_element_by_id("password").submit() time.sleep(5)
  #獲取token的方法:
  '''
1、要從Local Storage中獲取還是要從Session Storage中獲取,具體看目標系統存到哪個中-----開發者模式查看 2、window.SessionStorage和直接寫SessionStorage是等效的 3、一定要使用return,不然獲取到的一直是None 4、get的Item不一定就叫token,得具體看目標系統把token存到哪個變量中
  ''' token = driver.execute_script('return localStorage.getItem("token");') driver.close() return token

對於獲取項目存儲的信息位置信息,可以F12進行查看,如下圖:LocalStorage 和 SessionStorage

 

在實際的操作中,可能會遇到一些問題。由於瀏覽器靜默運行,無法看到具體頁面打開的情況,會造成一些莫名其妙的失敗問題。

異常影響:

  • 網速、網絡問題
  • 代碼問題

因此,我在頁面家引入了time模塊,進行相關等待時間的設置。解決了因為網速問題而導致腳本的失敗的問題


免責聲明!

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



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