3

I'm trying to use selenium webdriver to locate an element in html

size_element = driver.find_element(By.XPATH,"//span[text()= 'XL']")

The above works.

However, if I tried to represent "XL" with a string variable like below, it won't work.

size = "XL"

size_element = driver.find_element(By.XPATH,"//span[text()= f'{size}']")

similarly, the below don't work either:

size_element = driver.find_element(By.XPATH,"//span[text()= {}]".format(size)

size_element = driver.find_element(By.XPATH,"//span[text()= %s]"%size)
1
  • 1
    The f is in the wrong place. It needs to be at the beginning of the outer string: f"//span..." Commented Feb 22, 2022 at 0:17

2 Answers 2

2

“F-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should be noted that an f-string is really an expression evaluated at run time, not a constant value.

The below should work:

size = "XL"

size_element = driver.find_element(By.XPATH, f"//span[text()= {size}]")
Sign up to request clarification or add additional context in comments.

Comments

1

You should try:

size_element = driver.find_element(By.XPATH,f'//span[text()= {size}]')

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.