简体   繁体   中英

How to define a button with selenium without executing "find_element"? (Python)

I really like to pre-define locators and assign them to variables in my test automation project so I could just refer to the variable name later on like this:

login_button = <browser>.find_element_by_id("login")
login_button.click()

The problem is that if these locators are saved in 'File A' and I import this file into 'File B' (at the very beginning of the program) than those "find_element" methods are executed during the import process while the pages that contain those buttons are not loaded yet which of course leaves me with an exception.

How can I save buttons into variables and import the containing file in the very beginning?

You can store such variables as strings, eg:

login_button_click = "driver.find_element_by_id('login').click()"

And then when required use:

exec(login_button_click)

In my opinion, you should divide your files like this:

file_a:

def click_login(driver):
    login_elem = driver.find_element_by_id('login')
    login_elem.click()


def send_username(driver, username: str):
    login_elem = driver.find_element_by_id('username')
    login_elem.send_keys(username)


def send_password(driver, password: str):
    login_elem = driver.find_element_by_id('password')
    login_elem.send_keys(password)

file_b :

from file_a import *
from selenium import webdriver


driver = webdriver.Chrome()
username = "my_username"
password = "my_password"

def preform_login():
    send_username(driver, username)
    send_password(driver, password)
    click_login(driver)

For testing, you should use a config file config.ini for all your var's.

Again this is just my opinion...

Hope you find this helpful!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM