Reputation: 416
I'm trying to create a definition that allows me to click on an object regardless of the element type. To achieve this, I created a variable containing the command I want to run.
def clickOnStaleElement(driver, objStrategy, element):
lhs, rhs = objStrategy.split(".", 1)
myCommand = "driver.find_element_by_"+rhs.lower()+"(\""+element+"\").click()"
I can't seem to figure out how to execute this command that's stored in the variable. I tried 'driver.execute_script()' but received a WebDriverException. Trying 'exec()', & 'eval()' resulted in the text hanging. How do I achieve this? Is there a better way to go about achieving this behavior? I realize how I'm trying to achieve this behavior may not be ideal, so I'm open to better ways to accomplish the same task. I'd prefer not to create 'if/then' statements for each element type, if possible.
Upvotes: 0
Views: 436
Reputation: 385940
You can create a dictionary that provides a mapping from a string to a function, then do a simple lookup:
strategy = {
"id": driver.find_element_by_id,
"name": driver.find_element_by_name,
...
}
find_element = strategy.get(rhs.lower())
find_element(element).click()
You probably want to have a default method, or otherwise prepare for the case where rhs.lower()
doesn't match anything in the dictionary.
Upvotes: 2
Reputation: 3217
def clickOnStaleElement(driver, objStrategy, element):
lhs, rhs = objStrategy.split(".",1) #ASSUMING only valid stuff comes down like "???.xpath" , "???.name" "???.id" bla bla ... we'll just keep this here for now....
if rhs == 'xpath':
myCommand = driver.find_eleemnt_by_xpath(element) # xpath example, you better hope you entered valid xpath as "element"
elif rhs == 'id':
myCommand = driver.find_eleemnt_by_id(element)
elif rhs == 'name':
#you get the idea
.
.
.
else:
print("rhs, not recognized/valid/watever")
myCommand.click()
I would literally break it down to each having its own If statement on watever rhs
is.
Also in my opinion, theres no reason to ever pass in "???.somethng" like that into objStrategy, why not just pass in what you actually want?
Upvotes: 0