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!

#python #selenium

1 Likes77.65 GEEK