如何保存登录数据以供Python Selenium Webdriver识别 [英] How to save login data to be recognized for Python Selenium webdriver

查看:62
本文介绍了如何保存登录数据以供Python Selenium Webdriver识别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想保存登录数据(密码和登录名)以进行测试.我想将它们保存到可以某种方式识别的任何Webdriver中.编写每个脚本时,我不想一次又一次地将登录数据写入每个步骤.我试图将它们保存到浏览器中,但是该软件仍然无法识别它.

I want to save login data (password and login name) for testing purpose. I want to save them to any webdriver could recognize it in somehow. I do not want again and again writing my login datas into each steps when I write each script. I tried to save them into browser, but the software cannot recognize it anyway.

driver.find_element_by_xpath('//input[@type="text"]').send_keys("develop@*********.com")
driver.find_element_by_xpath('//input[@type="password"]').send_keys("*********")

推荐答案

您可以保存首次使用您的凭据登录后,下次您只需添加回cookie并自动进行身份验证即可.

You can save the cookies once you have logged in for the first time using your credentials so next time you can simply add back the cookies and get authenticated automatically.

使用 Selenium 演示Cookie的用法>我们已经使用的问题来存储Cookie,已登录网站 http://demo.guru99.com/test/cookie/selenium_aut.php .下一步,我们打开了同一个网站,添加了cookie,并能够以登录用户的身份登陆.

To demonstrate the usage of cookies using Selenium we have stored the cookies using pickle once the user had logged into the website http://demo.guru99.com/test/cookie/selenium_aut.php. In the next step, we opened the same website, adding the cookies and was able to land as a logged in user.

  • 用于存储cookie的代码块:

  • Code Block to store the cookies:

from selenium import webdriver
import pickle

options = webdriver.ChromeOptions() 
options.add_argument("start-maximized")
driver = webdriver.Chrome(options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get('http://demo.guru99.com/test/cookie/selenium_aut.php')
driver.find_element_by_name("username").send_keys("abc123")
driver.find_element_by_name("password").send_keys("123xyz")
driver.find_element_by_name("submit").click()
pickle.dump( driver.get_cookies() , open("cookies.pkl","wb"))

  • 代码块,用于使用存储的cookie进行自动身份验证:

  • Code Block to use the stored cookies for automatic authentication:

    from selenium import webdriver
    import pickle
    
    options = webdriver.ChromeOptions() 
    options.add_argument("start-maximized")
    driver = webdriver.Chrome(options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
    driver.get('http://demo.guru99.com/test/cookie/selenium_aut.php')
    cookies = pickle.load(open("cookies.pkl", "rb"))
    for cookie in cookies:
        driver.add_cookie(cookie)
    driver.get('http://demo.guru99.com/test/cookie/selenium_cookie.php')
    

  • 这篇关于如何保存登录数据以供Python Selenium Webdriver识别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆