如何让Selenium从Dashlane等密码管理器获取凭证用于自动化测试?
可行方案汇总
方法1:利用浏览器自动填充功能
密码管理器(如Dashlane)的核心功能之一就是自动填充浏览器表单,我们可以借助这一点让Selenium直接读取已填充的凭证:
- 确保目标浏览器(如Chrome)已安装并登录Dashlane插件,且插件已开启自动填充功能
- 启动Selenium时,加载浏览器的用户配置文件(而非默认临时配置),保留Dashlane的登录状态
- 打开目标网站登录页,等待几秒让Dashlane完成自动填充
- 通过Selenium定位用户名、密码输入框,获取其
value属性值
示例代码:
from selenium import webdriver from selenium.webdriver.common.by import By import time # 替换为你的Chrome用户配置文件路径 chrome_options = webdriver.ChromeOptions() chrome_options.add_argument(r"user-data-dir=C:\Users\YourUsername\AppData\Local\Google\Chrome\User Data") chrome_options.add_argument(r"profile-directory=Default") driver = webdriver.Chrome(options=chrome_options) driver.get("https://your-target-site.com/login") # 等待自动填充完成,时间按需调整 time.sleep(3) # 获取已填充的账号密码 username = driver.find_element(By.ID, "username").get_attribute("value") password = driver.find_element(By.ID, "password").get_attribute("value") # 提交登录 driver.find_element(By.ID, "login-button").click() driver.quit()
方法2:使用密码管理器的CLI工具
主流密码管理器大多提供命令行工具,Dashlane官方也有dashlane-cli,可以通过Python调用CLI命令提取凭证:
- 先安装Dashlane CLI并完成登录验证(按官方指引完成初始化)
- 在Python脚本中用
subprocess模块执行CLI命令,获取目标网站的凭证 - 解析命令输出,提取用户名和密码
示例代码:
import subprocess import json # 调用dashlane-cli获取指定网站凭证,替换为目标网站域名 result = subprocess.run( ["dashlane-cli", "get", "your-target-site.com"], capture_output=True, text=True ) # 解析CLI返回的JSON格式结果 credentials = json.loads(result.stdout) username = credentials["login"] password = credentials["password"] # 用Selenium完成登录 from selenium import webdriver from selenium.webdriver.common.by import By driver = webdriver.Chrome() driver.get("https://your-target-site.com/login") driver.find_element(By.ID, "username").send_keys(username) driver.find_element(By.ID, "password").send_keys(password) driver.find_element(By.ID, "login-button").click() driver.quit()
注意事项
- 自动填充方法依赖浏览器插件状态,插件更新或浏览器配置变更可能导致失效
- CLI方法稳定性更高,但需确保CLI已正确配置,且绝对不要在脚本中硬编码敏感验证信息(如CLI登录令牌)
- 无论采用哪种方案,都要严格保障测试环境的安全性,避免凭证泄露
内容的提问来源于stack exchange,提问作者Thibs
相关产品推荐
相关产品推荐

