Home > database >  How to pass variables to represent a string in xpath - Selenium
How to pass variables to represent a string in xpath - Selenium

Time:02-22

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)

CodePudding user response:

You should try:

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

CodePudding user response:

“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}]")
  • Related