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.
-
Possible duplicate of how to cast a variable in xpath pythonAndersson– Andersson2018年04月25日 04:59:04 +00:00Commented Apr 25, 2018 at 4:59
2 Answers 2
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()
Comments
@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")