Search code examples
pythonseleniumpyyaml

Yaml config file contains webdriver.Firefox() method as a parameter, how to convert string so it can be assigned to driver function


Here is my yaml file

conf_driver: # Comment all but one to choose browser
    #driver: webdriver.Chrome()
    driver: webdriver.Firefox()
    #driver: webdriver.Edge()
    #driver: webdriver.Safari()

Here is my python code

# Load YAML file configuration

with open('config.yml') as f:
    config = yaml.load(f, Loader=yaml.FullLoader)

driver = config['conf_driver']['driver']
print(driver)
driver.get(config['conf_url_member']['url]'])

Here is the result from running my code

    webdriver.Firefox()
Traceback (most recent call last):
  File "C:\Users\james.potter\PycharmProjects\SBCStructure\main.py", line 43, in <module>
    driver.get(config['conf_url_member']['url]'])
AttributeError: 'str' object has no attribute 'get'

Process finished with exit code 1

I understand that I am essentially writing (string)'webdriver.Firefox()'.get()

What is the simplest way to convert the string retrieved from my yaml config file so it can be assigned properly as if I were doing:

driver = WebDriver.Firefox()

Instead of

driver = "WebDriver.Firefox()"

Solution

  • I figured it out eventually,

    Used return getattr(function, 'string')

    This will be interpreted as function.string

    More indepth:

    def Driver_Start(browserNo):
    """
    Returns 'webdriver.' + the corresponding value for browserNo
    :param browserNo: Choose value: 1 = chrome, 2 = firefox, 3 = edge
    :return: webdriver.config['conf_driver'][browserNo])(executable_path=config['conf_driver_path'][browserNo])
    """
    return getattr(webdriver, config['conf_driver'][browserNo])(executable_path=config['conf_driver_path'][browserNo])