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!

1
  • Duplicate of stackoverflow.com/questions/48083073/…. 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). Commented Feb 20, 2020 at 15:17

4 Answers 4

3

Try to use the following code:

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

Hope it helps you!

Sign up to request clarification or add additional context in comments.

2 Comments

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?
@ChiserAlexandru, this is built-in in string in Python: Here are some examples and documentation: docs.python.org/3.4/library/string.html#format-examples
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")

Comments

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.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.