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模块,进行相关等待时间的设置。解决了因为网速问题而导致脚本的失败的问题

原文地址:https://www.cnblogs.com/ruichow/p/11340476.html