Unable to pass a variable to a locator in Python -- RESOLVED

I have the following in Python 3.6:

name = ‘Jae Garik’

And when I try to pass in the variable like this:

self.driver.find_element_by_android_uiautomator(‘new UiSelector().text(f"{name}")’).click()

I get error:
selenium.common.exceptions.NoSuchElementException: Message: An element could not be located on the page using the given search parameters.

This didn’t work either:
self.driver.find_element_by_android_uiautomator(‘new UiSelector().text("\""+name+"\"")’).click()

It gave me the same error as above.

But if I do it with the literal string:
self.driver.find_element_by_android_uiautomator(‘new UiSelector().text(“Jae Garik”)’).click()

It works perfectly. Can anybody help with this issue? It feels like I’m missing something very small but I can’t figure it out.

This is how I do:

username = 'venkatesh'
el = self.driver.find_element_by_id('username_field')
el.click()
el.clear()
el.send_keys(username)

If you can share a screenshot with the field highlighted, I’ll answer better.

Venkatesh_Akula,

thanks for responding. I think you may have misunderstood the problem I am experiencing. In the example that you gave, it would be as if your first two lines were:

username = ‘venkatesh’
el = self.driver.find_element_by_id(username)

Capture
Capture1

In these screenshots, I’m trying to find the name Nat Gray and clicking on it. I’m attempting to accomplish that by passing the string as a variable into the locator.

If I pass in the literal string “Nat Gray” to the locator, it works fine.

But if I assign a variable like this:
name_to_pass = “Nat Gray”

And pass in the variable name_to_pass to the locator, it doesn’t work.

Ok got it :grinning:

name = 'Nat Gray'
username_locator_xpath =  '//android.widget.TextView[@text="{}"]'.format(name)

Modify your scripts according to the above sample, you should use .format() to resolve that issue.

Venkatesh_Akula,

Thanks for the solution. I was, however, hoping to avoid using xpath. But it works nonetheless!

Would you know why passing a var doesn’t work with the UiSelector?

Thanks,
Wai

I’m 0 in python, but your code from original post is

name = 'Jae Garik'
var1 = 'new UiSelector().text("\""+name+"\"")'
print(var1)
var1 = 'new UiSelector().text(f"{name}")'
print(var1)

And that prints

new UiSelector().text("""+name+""")
new UiSelector().text(f"{name}")

Maybe you looking for:

var1 = 'new UiSelector().text("'+name+'")'
print(var1)
var1 = 'new UiSelector().text("{}")'.format(name)
print(var1)

that prints:

new UiSelector().text("Jae Garik")

Telmo_Cardoso,

That works! That print function is such a simple test too. I hadn’t even thought to try that! Thank you so very much!

Wai

This may help in future Python debugging. You can check variable values from the Python shell as well:

Hi Wai Chu, I’m glad that you found a solution.

I thought you would make what Telmo Cardoso replied from the sample code which I posted.