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

Viewed 18
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.

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

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