Search code examples
pythonvariablesseleniumselenium-webdriver

Using a variable in xpath in Python Selenium


I've been having trouble figuring out how to get a variable to work Selenium. This post seems to have helped (Variable not working inside parenthesis) but I still can't get it to work.

When I used the actual value it works. In this case AL-Alabama. I created a variable called state so that I can just call that in my function. I have 13 states to run through.

driver.find_element_by_xpath("//option[@value='AL-Alabama']").click()

This one uses the state variable and in looking at error message it shows the variable value as AL-Alabama. So it seems like it's referencing the correct value in the web page. Not sure what I'm missing or why it's not working. Any guidance would be appreciated.

driver.find_element_by_xpath('//option[@value=' + state + ']').click()
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//option[@value=AL-Alabama]"}

Solution

  • The single quotes around the value are not present with how you coded it. Try:

    driver.find_element_by_xpath("//option[@value='" + state + "']").click()