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.

asked Apr 25, 2018 at 2:20
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()
answered Apr 25, 2018 at 2:27
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")
answered Apr 25, 2018 at 6:46

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.