Reputation: 123
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
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
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
Reputation: 6459
Try to use the following code:
variable = "my_text"
your_needed_xpath = "//*[contains(text(), '{}')]".format(variable)
Hope it helps you!
Upvotes: 3
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