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)
cruisepandey
29.5k6 gold badges23 silver badges43 bronze badges
asked Feb 21, 2022 at 23:32
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}]")
answered Feb 22, 2022 at 4:02
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}]')
cruisepandey
29.5k6 gold badges23 silver badges43 bronze badges
answered Feb 22, 2022 at 0:14

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.