-1
browser.find_element_by_xpath('//div[contains(text(), "SomeData")]')

I want to pass a variable instead of a string, I am using Selenuim with python. In this Case A div will be found with text of "SomeData" everytime instead of passing a value as string I want it a variable, which will change everytime I run the code.

5
  • Please be more specific. What do you exactly mean with "variable"? And provide a minimal working example. Commented May 12, 2018 at 18:43
  • I am passing a string to be found in the above case "String" is to be found. Everytime code runs it will find String in the div. but I want to change the value every time like there should be placed a variable Commented May 12, 2018 at 18:46
  • input=browser.find_element_by_partial_link_text(variable) see this @buhtz Commented May 12, 2018 at 18:46
  • Don't comment. Please edit your question and provide the informations there. Commented May 12, 2018 at 18:50
  • Possible duplicate of how to cast a variable in xpath python Commented May 12, 2018 at 19:05

1 Answer 1

0

I cannot give a correct answer as I am unable to fully understand your question. But lets assume, you want to have some part of your stated xpath as a variable, that part can be stored in a variable and then referenced in your function call. And my_variable can be controlled in your code and change value as needed without writing complete xpath

Again having said that, more clarity on your question will help the community help you bette

my_variable = 'SomeData'
browser.find_element_by_xpath(f'//div[contains(text(), "{my_variable}")]')

if you are using python version less that 3.6

my_variable = 'SomeData'
browser.find_element_by_xpath(f'//div[contains(text(), "{my_variable}")]'.format(my_variable=my_variable))

or syntax provided in the comment by Andersson

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

1 Comment

Note that f-strings syntax was added to Python 3.6 and this will not work with earlier interpreter versions. Common options are '//div[contains(text(), "%s")]' % "SomeData" and '//div[contains(text(), "{}")]'.format("SomeData")

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.