Using a variable in xpath in Python Selenium

前端 未结 3 1806
梦毁少年i
梦毁少年i 2020-12-31 10:25

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 ge

3条回答
  •  遥遥无期
    2020-12-31 10:51

    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()
      

    Best Practices

    Ideally. to click() on the element with respect to the variable value attribute of the tag using Selenium] and you need to to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

    • Using variable in XPATH:

      state = 'AL-Alabama'
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//option[@value='" +state+ "']"))).click()
      
    • Using %s in XPATH:

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

      state = 'AL-Alabama'
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//option[@value='{}']".format(str(state))))).click()
      
    • Note : You have to add the following imports :

      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.common.by import By
      from selenium.webdriver.support import expected_conditions as EC
      

    Reference

    You can find a couple of relevant discussions in:

    • How to find an element with respect to the user input using Selenium and Python?

提交回复
热议问题