2

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("*********")

2 Answers 2

2

You can save the 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.


Demonstration

To demonstrate the usage of cookies using Selenium we have stored the cookies using 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.

  • 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"))
    
  • 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')
    
0

it is simple you can save your logged-in session by doing the following:

in Ubuntu:

import os

dir_path = os.getcwd()

profile = os.path.join(dir_path, "profile", "facebook")

option.add_argument(r"user-data-dir={}".format(profile))

browser = webdriver.Chrome(options=option,executable_path='./chromedriver')

if you use windows it will only change the way of indicating the path of the chrome driver. If it has in its default system path, just delete this path indication (valid for both Linux and Windows)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.