Search code examples
pythonvariablesxpathselenium4

How to use variable instead of xpath value in Selenium ...find_element(By.XPATH, "xpath")


Is there a way to use variable instead of string value for the xpath?

I am using: driver.find_element(By.XPATH, "xpath-value-string")

But I need to replace the string (the xpath value) and use variable instead like this: my_xpath = "xpath-value-string" driver.find_element(By.XPATH, my_xpath) The goal is to pull various xpath values from the list and use them in for loop dynamically inserted as the xpath values. I have found some advices of using .format; str(); f"{my_xpath} etc. to insert the values but nothing was working. I am pyhton beginner. So maybe I am taking it wrong and it must be a string as the attribute not variable. Any ideas? Thank you.


Solution

  • Maybe something like this:

    xpaths = ['xpath_example_1', 'xpath_example_2']
    for xpath in xpaths:
        driver.find_element(By.XPATH, xpath)