0

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.

1

2 Answers 2

6

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()
Sign up to request clarification or add additional context in comments.

Comments

1

@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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.