Home > database >  How to pass in a variable value in XPATH element using python selenium
How to pass in a variable value in XPATH element using python selenium

Time:09-22

test = "Games"
driver.find_element(By.XPATH, "//div[@title = {test}]").click()

My code doesn't work. Please suggest how to pass in a variable value inside the XPATH.

CodePudding user response:

test = "Games"
driver.find_element(By.XPATH, "//div[@title = {}]".format(test)).click()

CodePudding user response:

To click() on the element with respect to the variable value attribute of the tag using Selenium and python you can use either of the following Locator Strategies:

Using variable in XPATH:

state = 'AL-Alabama'
driver.find_element(By.XPATH, "//option[@value='"  state  "']").click()
Using %s in XPATH:

state = 'AL-Alabama'
driver.find_element(By.XPATH, "//option[@value='%s']"% str(state)).click()
Using format() in XPATH:

state = 'AL-Alabama'
driver.find_element(By.XPATH, "//option[@value='{}']".format(str(state))).click()
  • Related