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

前端 未结 2 1002
天命终不由人
天命终不由人 2021-01-23 11:15

The following is the HTML structure:

12345

abc

相关标签:
2条回答
  • 2021-01-23 11:56

    Try the below xpath:

    code = '23456'
    element = driver.find_element_by_xpath("//p[@class='code' and text()='" +code +"']")
    
    0 讨论(0)
  • 2021-01-23 11:59

    To locate the element with respect to the input by the user using Selenium and python you need to to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

    • Using variable in XPATH:

      user_input = '23456'
      element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='list']//div/p[@class='code' and text()='" +user_input+ "']")))
      
    • Using %s in XPATH:

      user_input = '23456'
      element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='list']//div/p[@class='code' and text()='%s']"% str(user_input))))
      
    • Using format() in XPATH:

      user_input = '23456'
      element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='list']//div/p[@class='code' and text()='{}']".format(str(user_input)))))
      
    • 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
      
    0 讨论(0)
提交回复
热议问题