Reputation: 281
I have an xpath which works perfectly fine. Here is my code:
driver.find_element_by_xpath('//div[contains(text(), "aots-cm")]').click()
But "aots-cm" is a hard coded value. I want to pass a variable instead of hard coded value.
assetId = ("aots-cm")
my_var = ("'//div[contains(text()," + " " + '"' + assetId+ '"' + ")]'")
print (my_var)
=== > '//div[contains(text(), "aots-cm")]' ==> looks ok to me
driver.find_element_by_xpath(my_var).click()
There is error message Given xpath expression "'//div[contains(text(), "aots-cm")]'" is invalid: TypeError: The expression cannot be converted to return the specified type.
Upvotes: 0
Views: 333
Reputation: 193058
@SuperStew's answer is the best Pythonic way. Having said that you can also opt for an alternative by creating a function to accept a String
which will be passed from the main()
function as follows :
def click_me(myString):
driver.find_elements_by_xpath("//div[.='" + myString + "']").click()
Now, you can call this function with the required String
argument whenever and wherever required as follows :
click_me("aots-cm")
Upvotes: 1
Reputation: 3054
When you add the ()
around the string in my_var
you make it a tuple of length 1, and it needs to be a string. I would do it like so.
driver.find_element_by_xpath('//div[contains(text(), "{}")]'.format(assetID)).click()
Upvotes: 6