Search code examples
python-3.xselenium-webdriverconfigurationconfigconfiguration-files

Using python file as the data source for another one


I have the below code working very nice, I want to let the python file read the user and pwd from another file, so if I want to login to any other account, i will just change it in the file which is not the program source file, how can I do this?

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
import time
from time import sleep
import os
import sys



user = '.......'
pwd = '........'

driver = webdriver.Chrome()

driver.get('URL')
driver.maximize_window()
main_window = driver.current_window_handle

#wait username
wait_username = WebDriverWait(driver, 60)
wait_username.until(EC.element_to_be_clickable((By.ID,'..........')))

User_Name = driver.find_element_by_id("..........")
User_Name.send_keys(user)

#wait password
wait_password = WebDriverWait(driver, 60)
wait_password.until(EC.element_to_be_clickable((By.ID,'..........')))

Pass_Word = driver.find_element_by_id("..........")
Pass_Word.send_keys(pwd)


Solution

  • I would say that the easiest way to achieve what you want is to use configparser library. You would have to create an ini file, that would contain the data you need. Let's call this file config.ini

    [TestEnv]
    user = Zasados
    password = qwerty
    

    Then you would have to read contents of this file in your Python code:

    import configparser
    
    config = configparser.ConfigParser()
    config.read('config.ini')
    default_config = config['TestEnv']
    print(default_config['user']) # prints out Zasados
    print(default_config['password']) # prints out qwerty
    

    Using that approach would allow you to keep different sections with different credentials and then parametrize your script so you wouldn't have to edit any file. Keep in mind that for security reasons you shouldn't keep configuration files in your repository.