首页 > 解决方案 > Selenium 网站登录脚本。- 安全地存储凭据

问题描述

我编写了一个简短的脚本,用于使用 Python 的 Selenium 包登录网站。为了不在脚本中显式显示用户凭据,我将它们存储在单独的 JSON 配置文件中。

套餐:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
import time
import json

Webdriver初始化:

site_url = "mywebsite.com"
chrome_options = Options()

chrome_options.add_experimental_option("prefs", {
        "safebrowsing_for_trusted_sources_enabled": False,
        "safebrowsing.enabled": True
        })
    
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get(site_url)

通过 XPath 选择登录下拉元素、用户名和密码字段:

login_dropdown_path = """login_XPath"""
driver.find_element(By.XPATH, login_dropdown_path).click()
time.sleep(3)

username_field_path = """username_field_XPath"""
password_field_path = """password_field_XPath"""

username = driver.find_element_by_xpath(username_field_path)
username.clear()
password = driver.find_element_by_xpath(password_field_path)
password.clear()

使用存储的凭据打开 config.json:

with open('config.json','r') as f:
  config = json.load(f)

填写用户名和密码字段

username.send_keys(config['user']['username'])
password.send_keys(config['user']['password'])

单击通过其 XPath 标识的登录按钮:

login_button_path = """username_button_XPath"""
driver.find_element(By.XPATH, login_button_path).click()
time.sleep(3)

JSON文件是:

{
  "user": {
    "name": "username",
    "password": "password"
  }
}

该脚本仅供个人使用,但是否有更安全的方法来存储甚至可能加密凭据?

谢谢!

标签: pythonauthenticationencryptionselenium-chromedriver

解决方案


如果您只想避免以纯文本形式存储凭据,则可以对凭据文件本身进行加密/解密。当然,如果第三方知道如何解密加密文件,您将处于同一条船上,但它仍然是另一层。

https://github.com/M4cs/objcrypt可能就是这样一种解决方案。


推荐阅读