如何使用 Selenium 和 Python 查找与用户输入相关的元素?

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

下面是HTML结构:

<div class='list'>
  <div>
    <p class='code'>12345</p>
    <p class='name'>abc</p>
  </div>
  <div>
    <p class='code'>23456</p>
    <p class='name'>bcd</p>
  </div>
</div>

还有一个 config.py 供用户输入。如果用户输入23456到config.code,selenium如何得到pythonselect第二个对象?我正在使用 find_by_css_selector() 定位和 select 对象,但它只能 select 第一个对象,即 Code='12345'。我尝试使用 find_by_link_text(),但它是 <p> 元素而不是 <a> 元素。任何人都可以提供帮助......

试试下面的 xpath:

code = '23456'
element = driver.find_element_by_xpath("//p[@class='code' and text()='" +code +"']")

根据用户的输入定位元素 and you need to to induce for the visibility_of_element_located() and you can use either of the following :

  • 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+ "']")))
    
  • XPATH中使用%s:

    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))))
    
  • XPATH中使用format():

    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)))))
    
  • 注意:您必须添加以下导入:

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