Search code examples
pythonseleniumselenium-webdriverwebdriverwaitattributeerror

How do I put an attribute as a variable in a python function?


I have this function:

def webdriver_wait(browser, delay, tag_name, tag, succesful_message, fail_message):
    try:
        wait_by_var = WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.tag_name, tag)))
        print(succesful_message)
        return wait_by_var
    except TimeoutException:
        print(fail_message)

My problem comes when I execute the function. Due to the function variable tag_name, I get the following error:

AttributeError: type object 'By' has no attribute 'tag_name'

I want the attribute from By. to be as a variable in my function, so that when I call the function webdriver_wait() I can choose either a TAG_NAME,ÌD,XPATH,CSS_SELECTOR etc. The rest of the variables in the function i.e. browser, delay, tag etc all work.

How do I create a function where I can put an attribute of By. as a function variable?


Solution

  • Use the getattr() function to get an arbitrary attribute of a function by its name.

    getattr(By, tag_name)