我需要使用 selenium webdriver 登录到网页以下载一些 PDF,为此我需要使用 2 套我需要作为明文传递的凭据。
如果不对密码进行硬编码,最好的方法是什么?
我像这样对所有内容进行硬编码:
if __name__ == '__main__':
ooffice=[SECRET EXPUNGED]
luser=[SECRET EXPUNGED]
lpassword=[SECRET EXPUNGED]
muser=[SECRET EXPUNGED]
mpassword=[SECRET EXPUNGED]
logname="log.txt"
today=datetime.datetime.now()
with open(logname, 'a+') as f:
f.write("{}: program started \n".format(datetime.datetime.now()))
for i in range(3):
try:
with open(logname, 'a') as f:
f.write("{}: downloading first document, try:{} \n".format(datetime.datetime.now(),i+1))
simpledownload(ooffice,luser,lpassword)
break
except Exception as Argument:
with open(logname, 'a') as f:
f.write(str(Argument))
f.write("\n")
for i in range(3):
try:
simpledownload(ooffice,muser,mpassword)
with open(logname, 'a') as f:
f.write("{}: downloading second document, try:{} \n".format(datetime.datetime.now(),i+1))
break
except Exception as Argument:
with open('output.txt', 'a') as f:
f.write(str(Argument))
f.write("\n")
有时我会将密码存储在文本文件中,然后读取文本文件以获取密码。
with open(pw_file_location, 'r') as fil:
pw = fil.read()
您可以使用单独的配置文件或环境变量来存储它们。首先,您可以在与脚本相同的目录中创建一个名为“config.ini”的文件,内容如下。
[credentials]
luser = username1
lpassword = password1
muser = username2
mpassword = password2
然后在您的脚本中,使用 configparser 模块从配置文件中读取凭据。
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
luser = config['credentials']['luser']
lpassword = config['credentials']['lpassword']
muser = config['credentials']['muser']
mpassword = config['credentials']['mpassword']
现在您可以在登录代码中使用变量 luser、lpassword、muser 和 mpassword,而不是对值进行硬编码。