4

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!

Ratmir Asanov
  • 6,237
  • 5
  • 26
  • 40
  • Duplicate of https://stackoverflow.com/questions/48083073/add-variable-in-xpath-in-python. Spoiler: There's no clean way to do this with selenium, you have to rely on string interpolation or concatenation (which is what the current accepted answer does). – VLRoyrenn Feb 20 '20 at 15:17

4 Answers4

3

Try to use the following code:

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

Hope it helps you!

Ratmir Asanov
  • 6,237
  • 5
  • 26
  • 40
  • This worked just fine... but my I ask: how does that work? I mean... I understand that it creates the string needed for xpath, but how does the '{}')]".format(variable) work? – Chiser Alexandru Jan 29 '19 at 10:05
  • @ChiserAlexandru, this is built-in in string in Python: Here are some examples and documentation: https://docs.python.org/3.4/library/string.html#format-examples – Ratmir Asanov Jan 29 '19 at 10:10
1

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")
kerwei
  • 1,822
  • 1
  • 13
  • 22
1

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.

Mate Mrše
  • 7,997
  • 10
  • 40
  • 77
1

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)
KunduK
  • 32,888
  • 5
  • 17
  • 41