Chiser Alexandru
Chiser Alexandru

Reputation: 123

How to pass Python variable to XPath expression?

I am currently working on a script that prints the ID of an Web Element based on a given text. Up till now I managed to do this:

wait.until(lambda browser: browser.find_element_by_xpath("//*[contains(text(), 'my_text')]"))
ID = browser.find_element_by_xpath("//*[contains(text(), 'my_text')]").get_attribute("id")
print(ID)

The code works fine, but I want to change it so it can be used for strings other than "my_text".

How can I pass a variable to that function? Something like this:

variable = 'my_text'
wait.until(lambda browser: browser.find_element_by_xpath("//*[contains(text(), variable)]"))
ID = browser.find_element_by_xpath("//*[contains(text(), variable)]").get_attribute("id")
print(ID)

This way I could assign any text to the variable and use the same function every time.

Thanks!

Upvotes: 4

Views: 4925

Answers (4)

KunduK
KunduK

Reputation: 33384

You can try this as well.Hope it will work.

 variable = 'my_text'
 wait.until(lambda browser: browser.find_element_by_xpath("//*[contains(text(),'" + variable + "')]"))
 ID = browser.find_element_by_xpath("//*[contains(text(),'" + variable + "')]").get_attribute("id")
 print(ID)

Upvotes: 1

Mate Mrše
Mate Mrše

Reputation: 8444

Do the following - just enclose the variable in {}, and add an "f" before the string:

variable = 'my_text'
wait.until(lambda browser: browser.find_element_by_xpath(f'//*[contains(text(), {variable})]'))
ID = browser.find_element_by_xpath(f'//*[contains(text(),{variable})]').get_attribute("id")
print(ID)

This is called string interpolation.

Upvotes: 1

Ratmir Asanov
Ratmir Asanov

Reputation: 6459

Try to use the following code:

variable = "my_text"
your_needed_xpath = "//*[contains(text(), '{}')]".format(variable)

Hope it helps you!

Upvotes: 3

kerwei
kerwei

Reputation: 1842

You can format your xpath pattern first before feeding it to the method.

pattern = "//*[contains(text(), %s)]" % variable
ID = browser.find_element_by_xpath(pattern).get_attribute("id")

Upvotes: 1

Related Questions